当我尝试向构造函数分配静态属性时,打字稿出现错误:Property 'wheels' does not exist on type '() => void'.
如何告诉打字稿我的Car
对象可以有wheels
财产?
function Car() {
// do something
}
Car.wheels = 4 // throws: Property 'wheels' does not exist on type '() => void'.
const audi = new Car()
以上代码段可以在https://www.typescriptlang.org/play/index.html上进行测试
答案 0 :(得分:4)
function Car() {
// do something
}
namespace Car {
export let wheels = 4
}
const audi = new Car()
请参见handbook。
答案 1 :(得分:0)
使用一些杂技类型,重命名和多个变量,您可以使用type assertion来实现所需的功能:
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()
@MattMcCutchen建议的解决方案看起来更合法。