当前位置:网站首页>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
边栏推荐
- Interaction free shell programming
- [brush questions] most elements (super water king problem)
- CVPR 2022 | 大連理工提出自校准照明框架,用於現實場景的微光圖像增强
- [Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
- The time has come for the domestic PC system to complete the closed loop and replace the American software and hardware system
- Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
- Daily question - ugly number
- Design and implementation of kubelet garbage collection mechanism to protect nodes from being preempted by containers image GC high threshold
- 国产PC系统完成闭环,替代美国软硬件体系的时刻已经到来
- leetcode:297. Serialization and deserialization of binary tree
猜你喜欢

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

2022 P cylinder filling examination content and P cylinder filling practice examination video

SAP UI5 应用开发教程之一百零五 - SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍

CVPR 2022 | Dalian Technology propose un cadre d'éclairage auto - étalonné pour l'amélioration de l'image de faible luminosité de la scène réelle

Bisher - based on SSM pet adoption center

Nodejs Foundation: shallow chat URL and querystring module

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

Basic MySQL operations

pytorch是什么?pytorch是一个软件吗?

105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍
随机推荐
Taking two column waterfall flow as an example, how should we build an array of each column
2022 beautician (intermediate) new version test questions and beautician (intermediate) certificate examination
服务器无法远程连接原因分析
MPLS setup experiment
The 10th China Cloud Computing Conference · China Station: looking forward to the trend of science and technology in the next decade
Error in compiled file: error: unmapped character encoding GBK
Practical operation of vim
[brush questions] most elements (super water king problem)
Bisher - based on SSM pet adoption center
[Apple Photo Album push] IMessage group anchor local push
类的基础语法
[Blue Bridge Road - bug free code] pcf8591 - code analysis of AD conversion
CVPR 2022 | 大连理工提出自校准照明框架,用于现实场景的微光图像增强
Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
有监督预训练!文本生成又一探索!
第十届中国云计算大会·中国站:展望未来十年科技走向
Sklearn data preprocessing
Nodejs Foundation: shallow chat URL and querystring module
[set theory] set concept and relationship (true subset | empty set | complete set | power set | number of set elements | power set steps)
中移物联网OneOS与OneNET入选《2021年物联网示范项目名单》