简体   繁体   English

如何使用可选键声明 object?

[英]How to declare object with optional keys?

This code won't compile:此代码不会编译:

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

While this does:虽然这样做:

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

Why, and how to fix the first one?为什么,以及如何解决第一个问题?

PS附言

As a solution it's possible to use Partial but it doesn't look very nice:作为一种解决方案,可以使用Partial但它看起来不太好:

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

When you use index signature all the keys are optional by default because you're specifying only key's type ( string | number ) and its value type, not the actual required key.当您使用索引签名时,默认情况下所有键都是可选的,因为您只指定键的类型 ( string | number ) 及其值类型,而不是实际需要的键。 So you don't need to add ?所以不需要加? . .

interface A {
  [key: string]: string
}

Same with type alias :类型别名相同:

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

Or Record utility (same as type alias):记录实用程序(与类型别名相同):

type A2 = Record<string, string>;

type Partial<T> = { [P in keyof T]?: T[P] } is a mapped type . type Partial<T> = { [P in keyof T]?: T[P] }是一个映射类型 It creates new type based on another type and as in this example can make properties optional.它基于另一种类型创建新类型,并且在此示例中可以使属性成为可选的。 By the way Partial is included in typescript utility types, no need to redeclare it.顺便说一下, Partial包含在 typescript 实用程序类型中,无需重新声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM