我试图找到一种更优雅的解决方案来创建一种类型,该类型允许其索引签名的某些键是可选的。
这可能是泛型的一个用例,但我似乎无法破解它。
目前构建它是这样的:
// Required and optional keys allowed as indexes on final type
type RequiredKeys = 'name' | 'age' | 'city'
type OptionalKeys = 'food' | 'drink'
// Index types use to combine for final type
type WithRequiredSignature = {
[key in RequiredKeys]: string
}
type WithOptionalSignature = {
[key in OptionalKeys]?: string
}
// Build type with required and optional properties on index signature
type FinalType = WithRequiredSignature & WithOptionalSignature
// Test objects with functional autocomplete
const test1: FinalType = {
name: 'Test',
age: '34',
city: 'New York'
}
const test2: FinalType = {
name: 'Test',
age: '34',
city: 'New York',
drink: 'Beer'
}
const test3: FinalType = {
name: 'Test',
age: '34',
city: 'New York',
food: 'Pizza'
}