我想改变对象填充属性的方式。
目前我有
export interface INewOffer {
employment?: IEmployment;
heightWeight?: IHeightWeight;
}
export interface IEmployment{
trainings?: string;
activeEmployment?: string;
wage?: string;
}
创建对象的函数如下所示:
private dataGenerator(newCustomer: INewCustomer): INewOffer {
const data: INewOffer = {};
if (NullCheck.isDefinedOrNonNull(newCustomer.age)) {
data.employment = {
trainings: newCustomer.trainings,
activeEmployment: newCustomer.activeEmployment,
wage: newCustomer.wage,
};
} else {
data.employment = {
wage: newCustomer.wage,
};
}
data.heightWeight = {
height: '180',
weight: '75',
};
return data;
}
我试图将我的代码更改为
private dataGenerator(newCustomer: INewCustomer): INewOffer {
const data: INewOffer = {};
if (NullCheck.isDefinedOrNonNull(newCustomer.age)) {
data.employment.trainings = newCustomer.trainings;
data.employment.activeEmployment = newCustomer.activeEmployment;
data.employment.wage = newCustomer.wage
} else {
data.employment.wage = newCustomer.wage
}
data.heightWeight.height = '180';
data.heightWeight.weight = '75';
return data;
}
并且 VS 代码 IDE 没有发现任何问题,例如:当我将鼠标悬停在:
data.
它说const data: INewOffer
employment.
=>(property) INewOffer.employment?: IEmployment
wage
=>(property)IEmployment.wage?: string
但是当我运行测试时出现错误:
E/launcher - 错误:TypeError:无法设置未定义的属性“工资”
我试过这样设置:
data.employment!.wage = newCustomer.wage
但它不起作用。然后我发现 typescript 不支持可选链接。
我的问题是,为什么 IDE 不说这是一个错误?还是我必须做其他事情才能让它发挥作用?
最佳答案
您应该确保启用 --strictNullChecks
, 一个 compiler option .大概你有一个 tsconfig.json
在你的项目中归档;你应该在那里指定它。事实上,我建议使用 --strict
,其中包括 --strictNullChecks
以及其他有用的东西。这应该有望开始警告你这样的错误:
data.employment.wage // error!
// ~~~~~~~~~~~~~~~ <-- Object is possibly undefined.
加感叹号也无济于事;这是一个non-null assertion ,这意味着您是在告诉编译器,即使它认为该对象可能未定义,您也确信它不是。这基本上与您遇到的问题相反。如果你这样做:
data.employment!.wage // no error now
它将抑制 --strictNullChecks
打开的错误,但由于您对编译器撒谎,它会在运行时爆炸。该断言适用于这样的情况:
// this ends up setting data.employment to {} but the compiler doesn't realize it
Object.assign(data, { employment: {} });
data.employment.wage // error! but we know it *is* defined
// ~~~~~~~~~~~~~~~ <-- Object is possibly undefined.
data.employment.wage // no error now
TypeScript 的类型系统仅存在于设计时(当您编写程序时)并且完全是 erased来自运行的发出的 JavaScript。如果您希望进行运行时检查,则需要编写该运行时检查,并让 TypeScript 的类型检查器验证您是否已这样做:
data.employment = {}; // set the property in a way the compiler recognizes
data.employment.wage; // no error now
TypeScript 确实尝试为提议的 JavaScript 功能提供实现,并且最终可能会支持 optional chaining在 JavaScript 中,但当前提案仅位于 Stage 1 ,并且 TypeScript 维护者的一般政策是仅在语言达到第 3 阶段后才实现语言添加。因此 TypeScript 不支持可选链接 yet从 TS3.4 开始。
好的,希望对你有帮助。祝你好运!
关于typescript - 如何在 TypeScript 中使用可选链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55533564/