打字稿:声明与另一个类型相同的变量

zac*_*caj 6 typescript

有没有办法用另一个变量的类型声明一个变量?例如,我声明了一个具有某种类型的类成员,然后我想在同一类型的函数中声明另一个变量。但我不想修改原始声明,也不想复制它。似乎您应该能够执行以下操作:

class Foo {
    bar: {[key: string]: string[]};

    func() {
        const x: TypeOf<Foo.bar> = {};
        ....
    }
}
Run Code Online (Sandbox Code Playgroud)

我听说过专门针对函数返回类型的类似内容,但我再也找不到了...

Iva*_*van 12

您可以使用typeof,但在课堂上您应该使用属性:

class Foo {
    bar: {[key: string]: string[]};

    func() {
        const x: typeof Foo.prototype.bar = {};
        // here x has type `{[key: string]: string[]}`
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个课外的例子:

class A {
    b: string = ''
}

type test = typeof A.prototype.b // type is `string`
Run Code Online (Sandbox Code Playgroud)

操场