JavaScript data types
ECMAScript defines 8 data types
7 primitive types
Boolean
Null
Undefined
Number
BigInt(ES10)
String
Symbol
1 reference type
Object
TypeScript type
A few points to note
- The unitypes union type value can be one of multiple types
// 变量
let unitTypsVar: Number | String | Object;
unitTypsVar = {
}
console.log(unitTypsVar)
// 指定数组元素类型
let typesArr : (number | string | Object) [] = [1,2,3,'4',{
}]
- never type
Indicates that the end of the function cannot be executed
let fnNever: () => never = () => {
throw new Error('never')
}
function infiniteLoop(): never {
while (true) {
}
}
- Tuple
Tuple Tuple originated from functional programming, specifying the array type and the number of array elements
let tuple : [string,number,object] = ['a',1,{
}]
- Function type
To define the function type, first define the formal parameter list, and then use => to define the function return value type
let sumCust: (x: number, y?: number) => number;
sumCust = function sum(x: number, y?: number) {
typeof y === "number" && (x += y)
return x
}
Type alias
Use type to define type aliases to simplify the code and facilitate type reuse
function sum(x: number, y: number): number {
return x + y
}
// 抽取类型
type sumType = (a: number, b: number) => number
// 复用
const sum2: sumType = sum
sum2(1, 2)
Type assertion
Sometimes we need to access the properties and methods of the type when we are not sure about the type, but at this time the compiler will often report an error
Type assertion is to tell the compiler that you know the type better than it, and it shouldn’t make an error because of it
// 类型断言
type inputType = string | number;
function getLength(input: inputType): number {
return (input as string).length ? (input as string).length : (input as number).toString().length
// 另一种断言写法
// return (<string>input).length ? (<string>input).length : (<number>input).toString().length
}
getLength('a')
getLength(123)