gpt4 book ai didi

typescript - 将具有可为空字符串属性的接口(interface)转换为字符串属性

转载 作者:行者123 更新时间:2023-12-04 11:29:43 27 4
gpt4 key购买 nike

我有以下两个接口(interface),一个允许可以为空的 vin ,另一个没有:

interface IVehicle {
vin: string | null;
model: string;
}

interface IVehicleNonNullVin {
vin: string;
model: string;
}
我希望能够从 IVehicle 转换模型至 IVehicleNonNullVin在我能够推断出的执行路径中 vin不是 null .
考虑这个例子:
const myVehicle: IVehicle = {
vin: 'abc123',
model: 'm3'
};

const needsVin = (_: IVehicleNonNullVin) => false;

if (myVehicle.vin === null) {
throw new Error('null');
} else {
needsVin(myVehicle);
// ~~~~~~~~~~~~~~~~~~~ 'IVehicle' is not assignable to 'IVehicleNonNullVin'
}
返回以下错误:

Argument of type 'IVehicle' is not assignable to parameter of type 'IVehicleNonNullVin'.
Types of property 'vin' are incompatible.
Type 'string | null' is not assignable to type 'string'.
Type 'null' is not assignable to type 'string'.


即使我是 该属性在此处不可为空。
: 如何让 TS 相信现有模型符合基于代码流中的类型检查的类型?
Demo in TS Playground

解决方法
作为解决方法,我可以 铸型 (但这忽略了现有的类型安全):
needsVin(myVehicle as IVehicleNonNullVin);
建立新模型 (但这不能很好地扩展很多属性):
const nonNullVehicle: IVehicleNonNullVin = {
model: myVehicle.model,
vin: myVehicle.vin
}
needsVin(nonNullVehicle);

最佳答案

您可以使用 type predicate像这样定义用户定义的类型保护:

const isNonNullVin = (vehicle: IVehicle): vehicle is IVehicleNonNullVin =>{
return vehicle.vin !== null
}

if (!isNonNullVin(myVehicle)) {
throw new Error('null');
} else {
needsVin(myVehicle);
}

TypeScript will narrow that variable to that specific type if the original type is compatible.


Demo in TS Fiddle

关于typescript - 将具有可为空字符串属性的接口(interface)转换为字符串属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67989014/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com