I’m trying to find a more elegant solution for creating a type that allows certain keys of it’s index signature to be optional.
This may be a use case for generics, but I can’t seem to crack it.
Currently constructing it like this:
// 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'
}