简体   繁体   English

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

[英]What is the type of `typeof x` in typescript?

In typescript you can define a class like so: 在打字稿中,您可以这样定义一个类:

class Sup {

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

If you do the following: 如果您执行以下操作:

let x = Sup; 

Why is the type of x equal to typeof Sup (when I highlighted the type in vscode) and what does typeof Sup mean? 为什么x的类型等于typeof Sup (当我在vscode中突出显示类型时), typeof Sup是什么意思? Is this linked to the typeof operator? 这链接到typeof运算符吗?

Furthermore, how do you type something like let y = Object.create(Sup) ? 此外,如何键入let y = Object.create(Sup) Is this typed as let y: typeof Sup = Object.create(Sup) ? 是否将此类型设为let y: typeof Sup = Object.create(Sup)

typeof has a different meaning in TypeScript's type space than in normal JS. typeof在TypeScript的类型空间中的含义不同于在普通JS中的含义。 It's an operator to get the type of something that exists in the value space. 它是获取值空间中存在的内容类型的运算符。

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

So, when you assign SomeClass to a variable, the variable's type will be typeof SomeClass . 因此,当您将SomeClass分配给变量时,变量的类型将为typeof SomeClass The only reason it's not simplified like the above examples is because there's no way to non-ambiguously simplify the type of a class; 没有像上面的示例那样进行简化的唯一原因是,没有方法可以明确地简化类的类型。 it stays as typeof SomeClass for simplicity's sake. 为了简单起见,它仍然保持为typeof SomeClass的类型。

In your case, let x = Sup; 在您的情况下, let x = Sup; (or more precisely, inferred typeof Sup ) means that variable x can hold Sup constructor function but not the instance itself: (或更准确地说,是推断的typeof Sup )意味着变量x可以容纳Sup构造函数,但不能容纳实例本身:

class Sup { }

let x: typeof Sup;

x = Sup;       // ok
x = new Sup(); // invalid.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM