打字稿中`typeof x`的类型是什么?

时间:2018-06-13 15:15:14

标签: javascript typescript visual-studio-code

在打字稿中你可以像这样定义一个类:

class Sup {

    static member: any;
    static log() {
         console.log('sup');
    }
}

如果您执行以下操作:

let x = Sup; 

为什么x的类型等于typeof Sup(当我在vscode中突出显示类型时)和typeof Sup的含义是什么?这是否与typeof运营商相关联?

此外,您如何键入let y = Object.create(Sup)之类的内容? 输入的内容是let y: typeof Sup = Object.create(Sup)吗?

2 个答案:

答案 0 :(得分:2)

typeof在TypeScript的类型空间中具有与普通JS不同的含义。它是一个运算符,用于获取值空间中存在的某种类型。

let person = { name: 'bob', age: 26 }

type Person = typeof person // Person is { name: string, age: number }

// These are all equivalent
let personRef1: { name: string, age: number } = person
let personRef2: typeof person = person
let personRef3: Person = person
let personRef4 = person

// more examples
let secret = 'helloworld'
type Secret = typeof secret // string

let key = 123
type Key = typeof key // number

let add = (a: number, b: number) => a + b
type Add = typeof add // (a: number, b: number) => number

因此,当您将SomeClass分配给变量时,变量的类型将为typeof SomeClass。它不像上面的例子那样被简化的唯一原因是因为没有办法非模糊地简化类的类型;为了简单起见,它保持typeof SomeClass

答案 1 :(得分:1)

在您的情况下,let x = Sup;(或更准确地说,推断为typeof Sup)表示变量x可以保存Sup构造函数,但不能保存实例本身:

class Sup { }

let x: typeof Sup;

x = Sup;       // ok
x = new Sup(); // invalid.
相关问题