typescript - 如何在 typescript 的接口(interface)或对象文字类型中使某些属性成为必需但全部允许?

标签 typescript types

我想要一个对象类型,其中一些属性是必需的,但所有属性都是允许的。

例如:

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/

相关文章:

typescript - TS2339 : Property does not exist on union type - property string | undefined

Angular 单元测试 : Error: No value accessor for form control with name: 'phoneNumber'

angularjs - 如何使用 https ://angular. io/docs/ts/latest/guide/webpack.html 中的 vendor.ts

Typescript 类型/接口(interface) - 如果对象上存在某个属性,则任何其他属性均无效

javascript - 如何将棋子(图像)放入我的 div 标签?

sql - 在 PostgreSQL 中将(字符串)因子转换为数字

javascript - 如何使用打字克隆 typescript 中的对象

typescript - 嵌套选择定义

sql - SQL Server 2000 中用于存储视频的数据类型

haskell 错误: cannot derive well-kinded instance/kind-mismatch