此代码无法编译:
interface A {
[key: string]?: string
}
虽然这样做:
type Partial<T> = {
[P in keyof T]?: T[P]
}
为什么以及如何修复第一个?
P.S。
作为解决方案,可以使用Partial
,但看起来不太好:
type A = Partial<{
[key: string]: string
}>
答案 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
已包含在打字稿实用程序类型中,无需重新声明。