我希望能够初始化一个有或没有值的类。如果你传递一个值,那么一个类的所有方法都会期望这个值作为参数,并且该值将是你在初始化时传递的类型。
如果你什么都没传递,那么方法不会期望任何参数,并且值将是未定义的。
我认为代码会给出更好的例子:
class Foo<T = void> {
constructor(public type?: T) {}
bar = (type: T) => {
if (type) {
this.type = type;
}
};
}
const fooUndefined = new Foo();
fooUndefined.bar(); // no errors, this is ok
fooUndefined.type === undefined; // no errors, this is ok
fooUndefined.bar(1); // expected error, this is ok
const fooNumber = new Foo(0);
fooNumber.type === 1; // no errors, but type is `number | undefined`, this is not ok
fooNumber.type > 0; // unexpected error because type is `number | undefined`, this is not ok
fooNumber.bar(1); // no errors, this is ok
fooNumber.bar(); // expected error, need to pass number, this is ok
fooNumber.bar('1'); // expected error, strings are not acceptable, this is ok
所以type
房产在fooNumber
示例的类型为 number | undefined
.有没有办法在没有显式类型转换的情况下将其缩小到数字?Playground link
最佳答案
所有条件参数都得到 SomeType |不明确的。
你可以这样写绕过它。
转换到数字
fooNumber.type as number > 2
或者告诉 typescript 您确定使用 !表达。fooNumber.type! > 2
关于typescript - 类构造函数可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67094863/