关于TypeScript:typescript数据类型

39次阅读

共计 1398 个字符,预计需要花费 4 分钟才能阅读完成。

ts 反对的数据类型有:__Boolean、Number、String、Array、Tuple、Enum、Any、Void、Null、Undefined、Never、Object

Boolean、Number、String

let isBoolean: boolean = false
let number1: number = 123
let str1: string = `hello world`

Array 数组

let list1: number[] = [1, 2, 3]
let list2: Array<number> = [1, 2, 3]

Tuple 元组,一种非凡构造的数组

let x: [string, number] = ['123', 456]
x = ['456', 45678]

Enum 枚举, 等号前面为枚举值,默认从 0 开始,能够自定义

enum Color {
    Red = 'red',
    Green = 'green',
    Blue = 'blue'
}

enum Color1 {
    Red,
    Green,
    Blue
}

let c: Color = Color.Red

Any, 代表任意数据类型,无数据类型限度

let bool: any = false
bool = 'test'

Void 无数据类型或者在函数中无返回值,与 any 相同

function f(): void {console.log('this is void function')
}

Null and Undefined, 非凡的原始类型

let u: undefined = undefined
let n: null = null

Never 是所有类型的子类型,并且能够调配给每个类型,然而没有类型是 never 的子类型或者能够调配给 never,除了其自身

function error(message: string): never {throw new Error(message);
}

// Inferred return type is never
function fail() {return error("Something failed");
}

// Function returning never must have unreachable end point
function infiniteLoop(): never {while (true) {}}

Object 非原始类型也就是除 number,string,boolean,symbol,null 或 undefined 之外的类型

declare function create(o: object | null): void;
create({prop: 0}); // OK
create(null); // OK
create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error

类型断言 通常用作当 ts 无奈辨认某个值的详细信息时候强制类型转换有两种写法, 例如援用高德地图 ts 会报 amap undefined 谬误,可将 window 转为 any

let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

const {AMap} = window as any;

正文完
 0