Typescript:声明与另一个变量相同类型的变量

15

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

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

    func() {
        const x: TypeOf<Foo.bar> = {};
        ....
    }
}

我曾经听说过针对函数返回类型的类似东西,但是现在找不到了......


7
你可以写成 const x: Foo["bar"] = ... 来确定类型。 - ford04
类似的问题提供了更多的上下文。 - cachius
2个回答

12
你可以使用typeof,但在类中你应该获取属性:
class Foo {
    bar: {[key: string]: string[]};

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

另一个在类外的例子:

class A {
    b: string = ''
}

type test = typeof A.prototype.b // type is `string`

PlayGround


1
请考虑 typeof this['b'] - Aluan Haddad

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接