当前位置:网站首页>Basic types of data in TS
Basic types of data in TS
2022-07-03 04:08:00 【Next to the left hand is the right hand】
ts data type
ts Basic data type
After declaring the type , The type of variable cannot be changed
A vertical line | : Express or , Used to connect multiple types ( Joint type )
question mark ? For optional
& To express and
Boolean type boolean
let bool:boolean=true
Numeric type number
let num:number=10
String type string
let str:string=" I don't know what a rich woman is like when I'm young , Mistake beauty for treasure "
undefined type
const und:undefined=undefined
null type
const nul:null=null
null and undefined Are subtypes of other types , Can be assigned to any type
An array type Array
let arr:number[]=[1,2,3]
let arr:Array<number>=[10,20,30]
let arr:Array<nunber|string>=["hello",100,200]
After the array definition , The data type inside must be consistent with that when defining the array , Otherwise, an error will be reported
A tuple type tuple
let yuanZu:[string,number,boolean,undefined]=['haha',10,true,undefined]
A tuple is ts New data types , It can be understood as fixed length , An array of fixed data types for each location
Enumeration type enum
enum Color {
red,
blue,
yellow,
}
let color = Color.red;
console.log(color); //0
console.log(Color[2]); // yellow
enum Sex {
male = 1,
Woman ,
}
console.log(Sex. male ); //1
console.log(Sex[2]); // Woman
Each element in the enumeration has a number , The default from the 0 Start , It's incremented 1; But we can also define it ourselves ,eg from 1 Start
Enumeration can get the number through the element , You can also get the corresponding element by number
Elements can be directly in Chinese , But we don't recommend writing like this
any type
let anyType: any = 100;
anyType = " The bright moon in front of the window , Get up and open a window ; Get a slap in the face , All the teeth fall out ";
console.log(anyType);
let a: any[] = [false, 666, "hello"];
It can be any type , To use , But there is no error prompt when compiling ; It's equivalent to using js grammar
unknown type
and any be similar , You can assign values of any type to variables ;
But if you copy this variable to a variable of a known type ,unknow Will report a mistake , and any Can't
let unknowType: unknown;
unknowType = 10;
unknowType = "str";
console.log(unknowType);
let c = unknowType;
let d = 12;
d = unknowType; // This line will report an error , because d It has been inferred that it is a number , Can't be unknown Assigned to numeric type , And if it is any If you don't, you won't report an error ,undefined,null,any Can be assigned to any type
void type
function doSomething(): void {
const str: string = " As long as the rich woman holds , Move into the villa overnight ";
}
doSomething();
// to void assignment , It doesn't make much sense
// let vo: void = null/undefined;
When a function is declared , Use after parentheses void, It means that the function has no return value ( It is also equivalent to function return undefined or null)
object type object
interface Person {
age;
name;
height;
}
function getFitResult(obj: Person): object | boolean {
const singleMale = {
name: "Luca",
age: 24,
height: 180,
};
if (singleMale.age - obj.age <= 5 && singleMale.height - obj.height < 15) {
return singleMale;
} else {
return false;
}
}
const re = getFitResult({ name: "Ari", age: 24, height: 168 });
console.log(re);
let a:{name:“ The Monkey King ”}
let a={name:“ The Monkey King ”,age?:number}
let a={name:“luca”,[propName:string]:any} , There has to be name, There can also be other attributes of any type
Joint type union
let a:number|string=20
a="hello"
The representation can be one of many types
Form
| type | example | describe |
|---|---|---|
| number | 0,12,-20 | Arbitrary number |
| string | “hello” | Any string |
| boolean | true/false | Boolean value true/false |
| Literal | Its own | Limiting the value of a variable is changing the literal value ; It's a bit like const, Once declared, it cannot be changed |
| any | * | Any type , Set to any, It is equivalent to turning off... For this variable TS, And js almost |
| unknown | * | Type safe any |
| void | Null value (undefined) | No value ( or undefined); Mostly used for functions with no return value |
| never | No value | Cannot be any value , It can be used for function error |
| object | {name:“luca”} | Any object ;{} Used to specify which attributes are included in the object , Add Hello after attribute , Said the optional |
| array | [1,“fun”,true] | Any array |
| tuple | [4,5] | Tuples ,TS New type , Fixed length array |
| enum | enum{A,B} | enumeration ,TS New type |
| undefined | undefined | Subtypes of any type |
| null | null | Subtypes of any type |
Other related concepts
Types of assertions
Tell compiler , I know what type it is , Know what you're doing
grammar :
Variable as type
< type > Variable
function getLength(str: string | number) {
Because the received parameters may be arrays , The numbers don't have length, Direct use will report an error , So use type assertion to solve
if ((<string>str).length) {
// If there is a length , So it's a string
return (str as string).length;
} else {
return str.toString().length;
}
}
Type inference
If the variable type is not specified , According to the assignment , Infer a type
If the declaration is assigned at the same time , that TS The variable type can be detected automatically ; So declare and assign values , You can omit the declaration of the type
Only declare , No copy , The parser will set it to any( Implicit any)
let a=100 Infer as number
let b // Infer as any
边栏推荐
- Read a paper_ ChineseBert
- 【毕业季·进击的技术er】职场人的自白
- Esp32 series (3): GPIO learning (take simple GPIO input and output, ADC, DAC as examples)
- Database management tool, querious direct download
- Bisher - based on SSM pet adoption center
- Nodejs Foundation: shallow chat URL and querystring module
- C language hashtable/hashset library summary
- "Final review" 16/32-bit microprocessor (8086) basic register
- 树莓派如何连接WiFi
- 2022年已过半,得抓紧
猜你喜欢

Nodejs Foundation: shallow chat URL and querystring module

The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade

Arduino application development - LCD display GIF dynamic diagram

JS实现图片懒加载

Pdf editing tool movavi pdfchef 2022 direct download

300+篇文献!一文详解基于Transformer的多模态学习最新进展

第十届中国云计算大会·中国站:展望未来十年科技走向

2022 tea master (primary) examination questions and tea master (primary) examination question bank

Web session management security issues

Is pytorch open source?
随机推荐
JS native common knowledge
2022 beautician (intermediate) new version test questions and beautician (intermediate) certificate examination
sklearn数据预处理
2022 Shandong Province safety officer C certificate examination questions and Shandong Province safety officer C certificate simulation examination question bank
Analysis of the reason why the server cannot connect remotely
js/ts底层实现双击事件
Debug: CD cannot be used in kaggle
Competitive product analysis and writing
2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func main() { var a =
pytorch是什么?pytorch是一个软件吗?
MySQL create table
vim 的实用操作
Deep dive kotlin synergy (20): build flow
What is pytorch? Is pytorch a software?
Nodejs Foundation: shallow chat URL and querystring module
golang xxx. Go code template
Use of sigaction
Role of JS No
以两列的瀑布流为例,我们应该怎么构建每一列的数组
[mathematical logic] predicate logic (first-order predicate logic formula | example)