当前位置:网站首页>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
边栏推荐
- Without sxid, suid & sgid will be in danger- Shangwen network xUP Nange
- 【刷题篇】接雨水(一维)
- 用户体验五要素
- Dynamic programming: Longest palindrome substring and subsequence
- Commands related to the startup of redis under Linux server (installation and configuration)
- [mathematical logic] predicate logic (toe normal form | toe normal form conversion method | basic equivalence of predicate logic | name changing rules | predicate logic reasoning law)
- Debug: CD cannot be used in kaggle
- Reflection and planning of a sophomore majoring in electronic information engineering
- In Net 6 project using startup cs
- MySQL timestampdiff interval
猜你喜欢

nodejs基础:浅聊url和querystring模块
![[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification](/img/30/c840e28c0ef7c8ce574dcde4363863.jpg)
[Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification

105. SAP UI5 Master-Detail 布局模式的联动效果实现明细介绍

Deep dive kotlin synergy (19): flow overview

Cnopendata China Customs Statistics

IPv6 foundation construction experiment

How does the pytorch project run?

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

【刷题篇】接雨水(一维)

拆一辆十万元的比亚迪“元”,快来看看里面的有哪些元器件。
随机推荐
[mathematical logic] propositional logic (judgment of the correctness of propositional logic reasoning | formal structure is eternal truth - equivalent calculus | deduction from premise - logical reas
【刷题篇】 找出第 K 小的数对距离
js/ts底层实现双击事件
Error in compiled file: error: unmapped character encoding GBK
[graduation season · aggressive technology Er] Confessions of workers
How to connect WiFi with raspberry pie
有监督预训练!文本生成又一探索!
pytorch是什么?pytorch是一个软件吗?
Analysis of the reason why the server cannot connect remotely
Bisher - based on SSM pet adoption center
[mathematical logic] predicate logic (predicate logic basic equivalent | eliminate quantifier equivalent | quantifier negative equivalent | quantifier scope contraction expansion equivalent | quantifi
Database management tool, querious direct download
Arduino application development - LCD display GIF dynamic diagram
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
Interaction free shell programming
Half of 2022 is over, so we must hurry up
JS实现图片懒加载
Appium自动化测试框架
Deep dive kotlin synergy (19): flow overview
vim 的实用操作