Skip to content

TS中keyof、typeof关键字的作用 #138

Open
@GGXXMM

Description

keyof

keyof 索引类型查询操作符,用来获取索引类型的属性名,构成联合类型。(和JS中的 Object.keys 略有相似)

class Images {
    public src: string = 'https://www.google.com.hk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'
    public alt: string = '谷歌'
    public width: number = 500
}

type propsNames = keyof Images
// 等价于 type propsNames = "src" | "alt" | "width"

typeof

typeof,用来判断变量的类型。TS中还可以通过typeof获取一个变量的类型,并且可以用来声明新的变量。

let s = "hello";
let n: typeof s;
// 等价于 let n: string

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions