当前位置:网站首页>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
边栏推荐
- Cnopendata China Customs Statistics
- 2022 tea master (primary) examination questions and tea master (primary) examination question bank
- Wechat applet + Alibaba IOT platform + Hezhou air724ug build a serverless IOT system (III) -- wechat applet is directly connected to Alibaba IOT platform aliiot
- IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
- C language hashtable/hashset library summary
- 300+ documents! This article explains the latest progress of multimodal learning based on transformer
- pytorch项目怎么跑?
- Error in compiled file: error: unmapped character encoding GBK
- Is pytorch difficult to learn? How to learn pytorch well?
- Is pytorch open source?
猜你喜欢

Is pytorch open source?

Mutex and rwmutex in golang

In Net 6 project using startup cs

MPLS setup experiment

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

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

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

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

在 .NET 6 项目中使用 Startup.cs

CVPR 2022 | Dalian Institute of technology proposes a self calibration lighting framework for low light level image enhancement of real scenes
随机推荐
第十届中国云计算大会·中国站:展望未来十年科技走向
pytorch是什么?pytorch是一个软件吗?
Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
TCP, the heavyweight guest in tcp/ip model -- Kuige of Shangwen network
Appium自动化测试框架
The time has come for the domestic PC system to complete the closed loop and replace the American software and hardware system
MPLS setup experiment
毕设-基于SSM宠物领养中心
错误 C2694 “void Logger::log(nvinfer1::ILogger::Severity,const char *)”: 重写虚函数的限制性异常规范比基类虚成员函数
『期末复习』16/32位微处理器(8086)基本寄存器
[home push IMessage] software installation virtual host rental tothebuddy delay
Practical operation of vim
类的基础语法
js/ts底层实现双击事件
x Problem B
golang xxx. Go code template
The latest activation free version of Omni toolbox
[national programming] [software programming - Lecture Video] [zero foundation introduction to practical application]
C language hashtable/hashset library summary
Basic syntax of class