【发布时间】:2019-10-26 20:34:05
【问题描述】:
我想知道映射类型中的每个键是否都应该有一个定义的值。
我不希望会出现这种情况,因为它需要很多值。但是,我希望Partial<T> 可以分配给映射类型T,但事实并非如此。此外,从映射类型中读取值时,不需要检查 typeof value === 'undefined'。
type Mapped = { [key: string]: string };
// This works, so not all keys have to be defined
const mapped: Mapped = { 'a': 'b' };
// This is valid even with strict checks even though 's' is undefined
const s: string = mapped['c'];
const partialMapped: Partial<Mapped> = mapped;
// This doesn't work because `Partial<Mapped>` is of type `{ [key: string]: string | undefined }`
const secondMapped: Mapped = partialMapped;
由于{ 'a': 'b' } 可以分配给Mapped 变量,我希望Partial<Mapped> 也可以分配给Mapped,但不是。这是因为值undefined 与缺少键不同吗? Partial 上是否有一个变体使键可选?
【问题讨论】: