如何用可选键声明对象?

时间:2020-06-08 03:50:18

标签: typescript

此代码无法编译:

interface A {
  [key: string]?: string
}

虽然这样做:

type Partial<T> = {
    [P in keyof T]?: T[P]
}

为什么以及如何修复第一个?

P.S。

作为解决方案,可以使用Partial,但看起来不太好:

type A = Partial<{
  [key: string]: string
}>

1 个答案:

答案 0 :(得分:2)

使用index signature时,默认情况下所有键都是可选的,因为您仅指定键的类型(string | number)及其值类型,而不是实际所需的键。因此,您无需添加?

interface A {
  [key: string]: string
}

type alias相同:

type A1 = {
  [key: string]: string
}

Record utility(与类型别名相同):

type A2 = Record<string, string>;

type Partial<T> = { [P in keyof T]?: T[P] }mapped type。它根据另一个类型创建新类型,并且在本示例中可以使属性成为可选的。顺带一提,Partial已包含在打字稿实用程序类型中,无需重新声明。