I am on a quest to discover a more refined approach for creating a type that permits certain keys of its index signature to be optional.
Perhaps this is a scenario where generics would shine, but I have yet to unlock the solution.
At present, my construction method looks like this:
// Define required and optional keys allowed as indexes in the final type
type RequiredKeys = 'name' | 'age' | 'city'
type OptionalKeys = 'food' | 'drink'
// Create index types to combine into the final type
type WithRequiredSignature = {
[key in RequiredKeys]: string
}
type WithOptionalSignature = {
[key in OptionalKeys]?: string
}
// Construct the type with both required and optional properties in the index signature
type FinalType = WithRequiredSignature & WithOptionalSignature
// Test objects with autocomplete functionality
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'
}