typescript-数据类型

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 = [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 = (someValue).length;

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

const { AMap } = window as any;

你可能感兴趣的:(TypeScript)