Estoy tratando de encontrar una solución más elegante para crear un tipo que permita que ciertas claves de su firma de índice sean opcionales.
Este puede ser un caso de uso para genéricos, pero parece que no puedo descifrarlo.
Actualmente construyéndolo así:
// 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' }Su solución está bien si obtiene las claves dinámicamente. Si no es así, ¿por qué no simplemente hacer una interfaz?
interface FinalType { name: string; age: number; city: string; food?: string; drink?: string; }