【问题标题】:non-standard TypeScript interface/class fields非标准 TypeScript 接口/类字段
【发布时间】:2016-08-05 05:18:42
【问题描述】:

我正在处理JSON-Schema-faker project,我们使用以下 TypeScript 接口:

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

【问题讨论】:

标签: json class interface typescript


【解决方案1】:

我希望 TypeScript 只严格允许这四个字段:faker、chance、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

【讨论】:

    猜你喜欢
    • 2020-12-28
    • 2013-09-19
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    相关资源
    最近更新 更多