TypeScript初见 - 常见数据的类型

学习 · 2022-08-01

微信截图_20220801172635.png

了解TypeScript - JavaScript的超集

TypeScript是JavaScript类型的超集,它可以编译成纯JavaScript。
TypeScript可以在任何浏览器、任何计算机和任何操作系统上运行,并且是开源的。

码上知晓

// 1.基本数据类型定义
const uname: string = 'zuxing' // 字符了些定义
const age: number = 24 // 数字类型定义
const male: boolean = false // 布尔值
const undef: undefined = undefined // undefined
const nul: null = null
const obj: object = { uname, age, male }
const bigi: bigint = BigInt(9007199254740991)
const sym: symbol = Symbol('unique')

const tmp1: null = null
const tmp2: undefined = undefined

const tmp3: void = undefined

// 数组定义
const arrs: string[] = []
const arrs1: Array<string> = []
const arrn: number[] = []
const arrn1: Array<number> = []

const names: string[] = ['a', 'b', 'c', 'd']
const ages: [number, number, number] = [18, 20, 25]
const norml: [name: string, age: number] = ['zuxing', 24]

// 接口定义
interface User {
    name: string,
    age: number,
    other?: string // 标记可选属性
}
// 使用定义
const user: User = {
    name: 'zuxing',
    age: 24
}

interface UserOnly {
    readonly name: string, // 只读标记
    age: number,
    other?: string // 标记可选属性
}

const user1: UserOnly = {
    name: 'zuxing',
    age: 24
}

// user1.name = 'typescript' // 无法分配name,因为name是只读的

// 世界的尽头是Object
const o1: Object = Object(undefined)
const o2: Object = Object(null)
const o3: Object = Object(void 0)

const o4: Object = 'zuxing'
const o5: Object = 24
const o6: Object = { name: 'zuxing' }
const o7: Object = () => {}
const o8: Object = []

// 2.面量类型与枚举

// 模糊定义,可选值范围打
interface IRes {
    code: number;
    status: string;
    data: any;
}

const res1: IRes = {
    code: 200,
    status: 'ok',
    data: {
        name: 'zuxing' as string,
        age: 24 as number
    }
}

//使用联合类型加上字面量类型
interface IResA {
    code: 200 | 400 | 404 | 500;
    status: 'ok' | 'fail' | 'error';
    data: any;
}

const res2: IResA = {
    code: 500,
    status: 'error',
    data: {
        errmsg: 'system error!',
        path: '/path/to/error'
    }
}

// 判断题提示
declare var res3: IResA
if(res3.status === 'error') {}

// 枚举
// 常量枚举只需加const
// SC: const enum HttpStatus 
enum HttpStatus {
    Foo, // 不指定值就取0开始
    OK = 200,
    NOT_FOUND = 404,
    ERROR = 500,
    Bar // 不设置值就是 501
}


HttpStatus.Foo // 0
HttpStatus.ERROR // 500
HttpStatus.Bar // 501
typescript
Theme Jasmine by Kent Liao | 桂ICP备15008025号-6