hebtwo
hebtwo

Reputation: 1

Creating an index signature in Typescript with required AND optional keys

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

Upvotes: 0

Views: 1165

Answers (1)

Yftach
Yftach

Reputation: 752

Your solution is fine if you are getting the keys dynamically. If you arent then why not just do an interface?

interface FinalType {
   name: string;
   age: number;
   city: string;
   food?: string;
   drink?: string;
}

Upvotes: 1

Related Questions