Javascript typescript中的'typeof x'是什么类型?
在typescript中,您可以这样定义一个类:Javascript typescript中的'typeof x'是什么类型?,javascript,typescript,visual-studio-code,Javascript,Typescript,Visual Studio Code,在typescript中,您可以这样定义一个类: class Sup { static member: any; static log() { console.log('sup'); } } 如果您执行以下操作: let x = Sup; 为什么x的类型等于typeof Sup(当我在vscode中突出显示该类型时)以及typeof Sup的含义是什么?这是否与运算符的类型相链接 此外,如何键入类似于let y=Object.create(Sup
class Sup {
static member: any;
static log() {
console.log('sup');
}
}
如果您执行以下操作:
let x = Sup;
为什么x的类型等于typeof Sup
(当我在vscode中突出显示该类型时)以及typeof Sup
的含义是什么?这是否与运算符的类型相链接
此外,如何键入类似于let y=Object.create(Sup)
?
是否将其键入为让y:typeof Sup=Object.create(Sup)
?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
分配给变量时,变量的类型将是typeofsomeclass
。它没有像上面的例子那样简化的唯一原因是,没有办法不含糊地简化类的类型;为了简单起见,它保持为SomeClass的类型
(或者更准确地说,推断的typeof Sup
)意味着变量x
可以容纳Sup
构造函数,但不能容纳实例本身:
class Sup { }
let x: typeof Sup;
x = Sup; // ok
x = new Sup(); // invalid.
typeof
返回一个stringAhh,所以我想我可以得到它,也许我应该使用一个类型别名,比如type SupClass=typeof Sup
或者甚至type SupConstructor
或者type SupClone
?所以我可以给它多一点语义?