【问题标题】:Should TypeScript's mapped types have a value for every key?TypeScript 映射类型是否应该为每个键都有一个值?
【发布时间】: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&lt;Mapped&gt; 也可以分配给Mapped,但不是。这是因为值undefined 与缺少键不同吗? Partial 上是否有一个变体使键可选?

【问题讨论】:

    标签: typescript mapped-types


    【解决方案1】:

    您的代码可以关闭严格的空检查,因为您可以将 undefined 值分配给 string。我们这里说的是values,keys是无关紧要的!

    Mapped 的索引类型签名承诺没有特定的键,因此分配具有零个或多个键的类型将起作用。不允许分配非字符串值(如undefinednull),这是错误突出显示的内容。

    这是一个人为设计的示例,说明了该错误所要防范的内容:

    var undef: undefined;
    const partialMapped: Partial<Mapped> = {a: undef, b: undef}; // Works
    

    部分版本可以接受未定义的值。 “完整”版本不允许这样做。

    var undef: undefined;
    const mapped: Mapped = {a: undef, b: undef}; // Warnings!
    

    【讨论】:

      猜你喜欢
      • 2017-08-08
      • 2021-03-28
      • 1970-01-01
      • 1970-01-01
      • 2010-10-24
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多