Typescript - 一些骚操作

724 阅读1分钟

获取一个函数返回值类型

function getState() {
    return {
        foo: 7,
        bar: 'hello'
    };
}

type State = ReturnType<typeof getState>;

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

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

const defaultState = {
    foo: 7,
    bar: 'hello'
};

type PartialState = Partial<typeof defaultState>;

const partialState: PartialState = {
    foo: 8
};

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

const defaultState = {
    foo: 7,
    bar: 'hello'
}

type PickedState = Pick<typeof defaultState, 'foo'>

const partialState: PickedState = {
    foo: 8
}

// 不能将类型“{ foo: number; bar: string; }”分配给类型“Pick<{ foo: number; bar: string; }, "foo">”

调用静态方法 且 修改类名

class Foo {
    static bar = 'Oops!'

    getBarLength () {
        return (this.constructor as typeof Foo).bar.length
    }

    getBarUpperCase () {
        return (<typeof Foo>this.constructor).bar.toUpperCase()
    }
}


//  高级写法

class Foo {
    'constructor': typeof Foo
    static bar = "Oops!"

    getBarLength () {
        return (this.constructor as Foo).bar.length
    }

    getBarUpperCase () {
        return this.constructor.bar.toUpperCase()
    }
}

为函数添加静态属性

// js
function test () {}
test.cache = {}
// ts
function test () {}

namespace test {
  export const cache: object = {}
}

export default test