假设我有一个文字类型,定义为:
type MyKeys = 'a' | 'b' | 'c' | 'd'
我想声明一个类似于Record<MyKeys, number>
的映射类型,只是我只想填写我的密钥的一个子集.(实际上,文字有大约20个值).
我希望避免Partial
,因为它允许将潜在值指定为未定义.我想帮助开发人员确保,如果他们定义了一个值,那么它就是指定的.这在处理doing Object.entries
时也很有帮助,因为它可以避免处理未定义的值.
这里的情况是,我们有各种各样的插件需要配置,但不需要所有字段.比如:
// Use another type instead of Partial<Record<...>>
type ConfigType = Partial<Record<MyKeys, number>>
const PluginA: ConfigType = {
a: undefined, // Would be legal with Partial, but I'd like to block this
b: 25
};
const PluginB: ConfigType = {
c: 13,
d: 52,
};
const PluginC: ConfigType = {
a: 12,
d: 42,
};