简体   繁体   English

通过Typescript检查对象界面

[英]Check object interface via Typescript

Is there a best way to check an object against a typescript infterface? 有没有最好的方法来检查对象是否符合打字稿界面?

I am working between two schemas, where one extends the other. 我正在两种模式之间进行工作,其中一种扩展了另一种。 I need to convert the extension back to base, and am doing so by deleting props from the extension to shape it to the original base class. 我需要将扩展​​名转换回基类,并且通过从扩展名中删除props将其成形为原始基类来实现。 An example: 一个例子:

interface Base {
  prop1: string
  prop2?: string
  prop3?: string
}

interface Extended extends Base {
  prop4: string
  prop5: string
}

So in order to get Extended back to Base , I need to delete props prop4 and prop5 因此,为了使ExtendedBase ,我需要delete props prop4prop5

This is of course easy enough to do, but, I need to ensure that the final result conforms to the Base class, since deleting props does not tell the compiler anything , and the extension will pass the Base type check. 这当然很容易做到,但是,我需要确保最终结果符合Base类,因为删除props不会告诉编译器任何信息 ,并且扩展将通过Base类型检查。

I have looked at using a type guard, and other alternatives , however, I have not found a way to do this which accommodates for the optional properties found in Base , or a seemingly efficient way to do it. 我已经研究过使用类型保护和其他替代方法 ,但是,我还没有找到一种方法来适应Base的可选属性,或者这似乎是一种有效的方法。

Here is a basic plan for the type guard as well as handling optional props: 这是类型防护以及处理可选道具的基本计划:

function isBase(arg: any): arg is Base {
  return arg
    && arg.prop1
    && (arg.prop2 || true)
    && (arg.prop3 || true)
}

Besides being a lot of work for a lot of props, it's brittle. 除了要为许多道具做大量工作之外,它还很脆弱。 Soon as Base changes, this technique no longer works as intended. Base更改后,此技术将不再按预期工作。 I feel like there is (should be) some Typescript way via utility types that could check the props against the Base interface, so it will always work as intended. 我觉得通过实用程序类型有(应该)有一些Typescript方式可以对照Base接口检查道具,因此它将始终按预期运行。

Update 更新

I found this . 我发现了这个 Looks very close but could not get it working with interfaces. 看起来非常接近,但无法与接口一起使用。

If you need to keep Base as a standalone property, using composition instead of inheritance might be a better approach, for instance: 如果需要将Base保留为独立属性,则使用组合而不是继承可能是更好的方法,例如:

interface Base {
  prop1: string
  prop2?: string
  prop3?: string
}

interface Extended {
  data: Base
  prop4: string
  prop5: string
}

Do whatever is needed with Extended but only send data to database. 使用Extended执行所有需要的操作,但仅将data发送到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM