我想要一个对象类型,其中一些属性是必需的,但所有属性都是允许的。
例如:
type a = { b: any }
let c: a = { b: 2 } // works
let d: a = { b: 2, e: 3 } // error
最佳答案
好吧,一种方法是将两种类型组合在一起:
type Identifier = { id: string };
type SomeOtherData = Record<string, any>;
type DataWithId = Identifier & SomeOtherData; // <= use `&` to combine two types
// Works without any keys except `id`:
const test1: DataWithId = { id: 'test' };
// Works with `id` and more keys:
const test2: DataWithId = { id: 'test', other: 'various other things' };
// Intentionally does not work when `id` is missing:
const test3: DataWithId = { other: 'various other things' };
关于typescript - 如何在 typescript 的接口(interface)或对象文字类型中使某些属性成为必需但全部允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56946291/