属性“ zeroValue”没有初始化程序,也未在构造函数中明确分配

时间:2020-09-16 16:02:54

标签: typescript class object generics arguments

我正在学习打字稿,此代码与泛型(泛型类)相关,并且存在于typescript的文档中。这是什么问题?

class GenericNumber 
{ 
    zeroValue: T; 
    add: (x: T, y: T) => T; 
}

let myGenericNumber = new GenericNumber(); 
myGenericNumber.zeroValue = 0; 
myGenericNumber.add = function(x, y) 
{ 
    return x + y; 
};

错误:属性“ zeroValue”没有初始化程序,并且不确定 ts(2564)

1 个答案:

答案 0 :(得分:0)

共享TypeScript代码的最佳方法之一是将其发布到TypeScript playground

我认为您是在谈论this example

// you missed generic initializer
class GenericNumber<T> { // you missed generic initializer
// here TS compiler throws error because you only defined a type of class
// property, but you did not initialize it
    zeroValue: T; 

    add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber<number>(); // you missed generic initializer
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
    return x + y; // no error
};

工作示例

class GenericNumber<T> {
// to get rid of  error, you can define constructor 
// which takes [zeroValue] and [add] as arguments
    constructor(public zeroValue: T, public add: (x: T, y: T) => T){
        this.zeroValue = zeroValue;
        this.add = add;
    }
}
const zeroValue = 0;
let myGenericNumber = new GenericNumber<number>(zeroValue, (a,b)=>a+b);
const result = myGenericNumber.add(40,2) // 42

确保您的函数不会处理 this ,因为在这种情况下,您应该处理它