【问题标题】:What is the type of `typeof x` in typescript?打字稿中“typeof x”的类型是什么?
【发布时间】:2018-06-13 15:15:13
【问题描述】:

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

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)吗?

【问题讨论】:

  • typeof 返回一个字符串

标签: javascript typescript visual-studio-code


【解决方案1】:

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

【讨论】:

  • 啊,所以我想我明白了,也许我应该改用类型别名,例如 type SupClass = typeof Sup 甚至 type SupConstructortype SupClone?所以我可以给它更多的语义?
【解决方案2】:

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

class Sup { }

let x: typeof Sup;

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

【讨论】:

    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 2022-01-19
    • 2019-01-26
    • 1970-01-01
    • 2021-03-14
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多