如何解决使用联合,但得到道具不存在的错误
我有一个类型是联合的变量:
const waypoint: Waypoint;
Waypoint
类型是 2 种类型的联合:
type Waypoint = UtmNZ | GeoNZ;
export interface GeoNZ {
latitude: number;
longtitude: number;
}
export interface UtmNZ {
latitude: number;
longtitude: number;
zone: number;
}
后来我声明了一个接受这个联合的函数,需要在运行时决定参数的类型是 UtmNZ 还是 GeoNZ 并相应地使用函数 renderUTM()
或 renderGeo()
之一。
这是需要在运行时计算 Waypoint
实际类型的函数:
renderWaypoint(waypoint: Waypoint): string {
if(!waypoint?.latitude || !waypoint?.longtitude) return 'נ.צ. לא תקין';
if ('zone' in this.waypoint)
return renderUTM(waypoint);
else
return renderGeo(waypoint);
}
这里是具体的渲染函数签名:
function renderGeo(waypoint: GeoNZ): string
function renderUTM(waypoint: UtmNZ): string
我收到一个错误,提示 waypoint
缺少一个应该存在的 prop,多亏了 union。
解决方法
您可以使用 User-Defined Type Guards。
类型保护是一些执行运行时检查的表达式,以保证某个范围内的类型。
要定义类型保护,我们只需要定义一个返回类型为类型谓词的函数。 waypoint is UtmNZ
是本例中的类型谓词。谓词采用 parameterName is Type
形式,其中 parameterName
必须是当前函数签名中的参数名称。
例如
type Waypoint = UtmNZ | GeoNZ;
export interface GeoNZ {
latitude: number;
longtitude: number;
}
export interface UtmNZ {
latitude: number;
longtitude: number;
zone: number;
}
class Example {
waypoint = {
zone: 1,};
renderWaypoint(waypoint: Waypoint): string {
if (!waypoint.latitude || !waypoint.longtitude) return 'נ.צ. לא תקין';
if (isUTM(waypoint)) return renderUTM(waypoint);
else return renderGeo(waypoint);
}
}
function isUTM(waypoint: Waypoint): waypoint is UtmNZ {
return 'zone' in waypoint;
}
function renderGeo(waypoint: GeoNZ): string {
return 'geo';
}
function renderUTM(waypoint: UtmNZ): string {
return 'utm';
}
const utm: Waypoint = { zone: 123,latitude: 123,longtitude: 321 };
const exmaple = new Example();
console.log(exmaple.renderWaypoint(utm)); // output: utm
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。