簡體   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