typescript - 如何断言某些东西符合没有函数的类型?
问题描述
我想检查我创建的对象是否符合某个接口,但我也想保持原始类型不变。
我知道我可以像这样使用立即调用的函数表达式来实现这一点......
interface MustHaveThingy {
thingy: any;
}
const originalType = (function<T extends MustHaveThingy>(obj: T) {return obj;})({
thingy: 'something',
somethingElse: 'this is part of the type',
});
的类型
originalType
被键入为,{thingy: string; somethingElse: string;}
但它仍然符合 interfaceMustHaveThingy
。
......但它有点丑陋。有没有什么方法可以在没有立即调用的函数表达式的情况下实现上述目标?
我正在寻找的是整体——<code>T 扩展 SomeOtherType,其中T
推断出的实际类型但T
必须符合SomeOtherType
——但没有函数。
解决方案
您可以as
在单独的语句中使用。
interface MustHaveThingy {
thingy: any;
}
const originalType = {
thingy: 'something',
somethingElse: 'this is part of the type',
};
originalType as MustHaveThingy; // <- assertion
删除thingy: 'something'
线给出:
foo.ts(9,1): error TS2352: Type '{ somethingElse: string; }' 不能转换为类型 'MustHaveThingy'。类型 '{ somethingElse: string; 中缺少属性 'thingy' }'。
推荐阅读
- json - 使用自定义 json 响应进行 Laravel 验证
- ios - 如何从 Appdelegate 打开 Viewcontroller?
- angular - ExpressionChangedAfterItHasBeenCheckedError / Angular 4-Angular 7
- git - 如何在 Visual Studio 中从 TFS visualstudio.com 移动到 GitHub?
- java - 是否有任何解决方案通过使用 POP 在 Java 中传递特定的电子邮件消息 ID 来下载电子邮件附件?
- c# - 如何在 asp.net owin api 项目中启用 JSON.NET 序列化/反序列化跟踪?
- excel - 是否可以直接在 Excel 中打开带有逗号和分号(分号作为分隔符)的 CSV/Txt 文件并将其保存回来而不失真?
- php - 插入现有值并从另一个表中对其进行排序
- woocommerce - Woocommerce:覆盖现有电子邮件所需的登录。将订单添加到用户帐户
- amazon-web-services - 按需扩展 ec2 , lambda 风格