简体   繁体   English

扩展递归 Typescript 接口

[英]Extending recursive Typescript interfaces

I'm using the TS type for JSON Schema: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/json-schema/index.d.ts我正在为 JSON Schema 使用 TS 类型: https : //github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/json-schema/index.d.ts

Short version:精简版:

interface JSONSchema4 {
  properties?: {
    [k: string]: JSONSchema4;
  } | undefined;
}

This type is recursive.这种类型是递归的。 I'd like to extend this type with custom properties.我想用自定义属性扩展这种类型。 Eg currently, something like this doesn't match the type:例如目前,这样的事情与类型不匹配:

{ instanceof: 'Date' }

I'd like to add instanceof?: string as a field to JSONSchema4 .我想将instanceof?: string作为字段添加到JSONSchema4 Is this possible?这可能吗?

In TypeScript, interfaces are open, unlike types that are closed.在 TypeScript 中,接口是开放的,与封闭的类型不同。 So, you can add your keyword simply by declaring an interface with the same name that contains your keyword.因此,您可以简单地通过声明一个包含您的关键字的同名接口来添加您的关键字。 That interface effectively extends the original type.该接口有效地扩展了原始类型。

interface JSONSchema4 {
  instanceof?: string;
}

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

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