Typescript 如何使密钥成为可选的?
代码如下:Typescript 如何使密钥成为可选的?,typescript,Typescript,代码如下: type TypeKey = 'A' | 'B' | 'C' type Types = { [key in TypeKey] : string} let myTypes : Types = { A : 'Apple', B : 'Banna' } 这将有一个错误: error: TS2741 [ERROR]: Property 'C' is missing in type '{ A: string; B: string; }' but required in t
type TypeKey = 'A' | 'B' | 'C'
type Types = { [key in TypeKey] : string}
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}
这将有一个错误:
error: TS2741 [ERROR]: Property 'C' is missing in type '{ A: string; B: string; }' but required in type 'Types'.
如何使“C”可选?谢谢可能有一种更优雅的方法,但您可以通过从类型中删除
C
,然后将其作为可选属性添加回来:
type TypeKey = 'A' | 'B' | 'C'
// Remove C vvvvv−−−−−−−−−−−−−−−−−−−−−−−−−−−−vvvvvv
type Types = Omit<{ [key in TypeKey] : string}, 'C'> & {C?: string}
// Add it back as an optional property −−−−−−−−−−−−−−^^^^^^^^^^^^^^
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}
您可以用更通用的方式编写它,如下所示:
键入TypeKey='A'|'B'|'C'
类型类型={[key in TypeKey]:string}
类型可选=部分(&O)
常量myTypes:可选={
A:‘苹果’,
B:‘班纳’
}
这很有效,但还有更好的方法吗?类似于键入TypeKey='A'|'B'|'C?'@sqllyw-我已经通过添加到答案中来回复该评论。:-)
interface Types {
A: string;
B: string;
C?: string;
}
type TypeKey = keyof Types;
let myTypes : Types = {
A : 'Apple',
B : 'Banna'
}