Typescript有什么冷门但是很好用的特性?

前端精髓

共 1652字,需浏览 4分钟

 ·

2021-09-24 23:55

获取一个值的类型

let defaultState = {    foo: 7,    bar: 'hello'};
type State = typeof defaultState;
let nextState: State = { foo: 'seven', bar: 'world'};// 不能将类型“{ foo: string; bar: string; }”分配给类型“{ foo: number; bar: string; }”。// 属性“foo”的类型不兼容。// 不能将类型“string”分配给类型“number”。


获取一个函数的返回值的类型

function getState() {    return {        foo: 7,        bar: 'hello'    };}
type State = ReturnType<typeof getState>;
let nextState: State = { foo: 'seven', bar: 'world'};// 不能将类型“{ foo: string; bar: string; }”分配给类型“{ foo: number; bar: string; }”。// 属性“foo”的类型不兼容。// 不能将类型“string”分配给类型“number”。


将一个类型中的所有属性都变成可选属性

let defaultState = {    foo: 7,    bar: 'hello'};
type PartialState = Partial<typeof defaultState>;
let partialState: PartialState = { foo: 8};


取出一个类型中的部分属性,生成另一个类型

let defaultState = {    foo: 7,    bar: 'hello'};
type PickedState = Pick<typeof defaultState, 'foo'>;
let partialState: PickedState = { foo: 8, bar: 'world'};// 不能将类型“{ foo: number; bar: string; }”分配给类型“Pick<{ foo: number; bar: string; }, "foo">”。// 对象文字可以只指定已知属性,并且“bar”不在类型“Pick<{ foo: number; bar: string; }, "foo">”中。


还有一些其他内置工具类型,可以在把鼠标放到 ReturnType 上,按 F12 查看

type Readonly<T> = {    readonly [P in keyof T]: T[P];}
type Partial<T> = { [P in keyof T]?: T[P];}
type Nullable<T> = { [P in keyof T]: T[P] | null;}
type Proxy<T> = { get(): T; set(value: T): void;}
type Pick<T, K extends keyof T> = { [P in K]: T[P];}
type Record<K extends string, T> = { [P in K]: T;}


浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报