简体   繁体   English

如何在构造函数上为静态属性定义类型

[英]How to define a type for a static property on a constructor function

I have a problem with typescript throwing an error when I try to assign a static property to a constructor function: Property 'wheels' does not exist on type '() => void'. 当我尝试向构造函数分配静态属性时,打字稿出现错误:我Property 'wheels' does not exist on type '() => void'. How can I tell typescript that my Car object can have wheels property? 如何告诉打字稿我的Car对象可以具有wheels属性?

 function Car() { // do something } Car.wheels = 4 // throws: Property 'wheels' does not exist on type '() => void'. const audi = new Car() 

Above snippet can be tested on https://www.typescriptlang.org/play/index.html 上面的代码段可以在https://www.typescriptlang.org/play/index.html上进行测试

function Car() {
    // do something
}

namespace Car { 
    export let wheels = 4
}

const audi = new Car()

See the handbook . 参见手册

With a bit of type acrobatics, renaming and multiple variables you can use a type assertion to achieve what you want: 通过使用一些类型的杂技,重命名和多个变量,您可以使用类型断言来实现所需的功能:

function Car_() {
    // do something
};

type TCar = typeof Car_ & { wheels: number };
const Car = (Car_ as TCar);

Car.wheels = 4; // throws: Property 'wheels' does not exist on type '() => void'.

const audi = new Car()

The solution suggested by @MattMcCutchen looks more legit though. @MattMcCutchen建议的解决方案看起来更合法。

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

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