首页 > 解决方案 > 如何断言某些东西符合没有函数的类型?

问题描述

我想检查我创建的对象是否符合某个接口,但我也想保持原始类型不变。

我知道我可以像这样使用立即调用的函数表达式来实现这一点......

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;}但它仍然符合 interface MustHaveThingy

......但它有点丑陋。有没有什么方法可以在没有立即调用的函数表达式的情况下实现上述目标?

我正在寻找的是整体——<code>T 扩展 SomeOtherType,其中T推断出的实际类型但T必须符合SomeOtherType——但没有函数。

标签: typescript

解决方案


您可以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' }'。


推荐阅读