繁体   English   中英

非标准TypeScript接口/类字段

[英]non-standard TypeScript interface/class fields

我正在JSON-Schema-faker项目上 ,我们在其中使用以下TypeScript接口:

interface IGeneratorSchema { faker?: any; chance?: any; } interface IGeneratorSchema { faker?: any; chance?: any; } ,例如: { "faker": "name.findName" }或: { "chance": { "bool": { "likelihood": 100 } } }

现在,我们需要引入对x-fakerx-chance字段的支持,这些字段在语义上与fakerchance相同,例如:

{ "x-faker": "name.findName" }或: { "x-chance": { "bool": { "likelihood": 100 } } }

我知道我无法在TypeScript界面​​中创建x-fakerx-chance字段。 问题是-我该如何克服? 我希望TypeScript仅严格允许这四个字段: fakerchancex-fakerx-chance

我希望TypeScript仅严格允许这四个字段:fakerr,机会,x-faker,x-chance

您可以声明字符串属性:

interface IGeneratorSchema {
    faker?: any;
    chance?: any;
    "x-faker"?: any;
    "x-chance"?: any;
}

const foo:IGeneratorSchema = { "x-faker": {} } // Okay
const bar:IGeneratorSchema = { bad: {} } // Error: unknown property

警告

仅在新的对象文字情况下才阻止额外成员: https : //basarat.gitbooks.io/typescript/content/docs/types/freshness.html

暂无
暂无

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

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