0

我试图找到一种更优雅的解决方案来创建一种类型,该类型允许其索引签名的某些键是可选的。

这可能是泛型的一个用例,但我似乎无法破解它。

目前构建它是这样的:

//  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'
}
4

1 回答 1

1

如果您动态获取密钥,则您的解决方案很好。如果你不是那么为什么不做一个界面呢?

interface FinalType {
   name: string;
   age: number;
   city: string;
   food?: string;
   drink?: string;
}
于 2022-02-15T16:06:09.923 回答