如何定义一个以联合作为键但也有可选键的记录?

ros*_*ani 5 typescript type-definition

这是我的字典:

type Words = 'man' | 'sun' | 'person'
type Dictionary = Record<Words,string>
Run Code Online (Sandbox Code Playgroud)

并且Dictionary等于这种类型:

type Dictionary = {
    man: string;
    sun: string;
    person: string;
}
Run Code Online (Sandbox Code Playgroud)

目标是其他程序员知道应该使用 IDE 自动完成功能将女巫单词添加到字典中。但它限制他们添加其他可选单词。我尝试了这个,但结果根本不包含单词:

type Words = 'man' | 'sun' | 'person' | string
type Dictionary = Record<Words,string>
// Equals to 
type Dictionary = {
    [x: string]: string;
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能自动完成单词但也可以有可选单词?

小智 14

您可以使用Partial实用程序类型来保留泛型类型声明的功能,而不需要拥有所有所需的键。

type Dictionary = {
  man: string;
  sun: string;
  person: string;
  word: Partial<Record<Words, string>>;
};
Run Code Online (Sandbox Code Playgroud)

我意识到这个问题已经很老了,但它是搜索这个问题的一些变体时的最佳结果,所以我认为在这里添加这个是合适的。


ros*_*ani 1

解决方案是显式定义字典,不使用 Record 和 Union 类型。像这样:

type Dictionary = {
  man: string;
  sun: string;
  person: string;
  [word:string]:string;
}
Run Code Online (Sandbox Code Playgroud)