Rains-episode
Rains-episode

Reputation: 133

How to declare a "Record" type with partial of specific keys in typescript?

Now, I got this:

type T_PlatformKey= 'pf1' | 'pf2' | 'pf3'
type T_PlatformInfo = {
    key: T_PlatformKey
    name: string
    [k: string]: any
}

I'd like to declare a "Record" type like this:

type T_platforms = Record<T_PlatformKey, T_PlatformInfo>

const platforms: T_Platforms = {} // here is the problem

If i don't declare all properties:

Type '{}' is missing the following properties from type 'Record<T_PlatformKey, T_PlatformInfo>': pf1, pf2, pf3 ts(2739)

I've tried other way like this:

interface I_Platforms {
    pf1: T_PlatformInfo
    pf2: T_PlatformInfo
    pf3: T_PlatformInfo
}
const platforms: Partial<I_Platforms> = {} // it works

uh, it works, but...? not very smart.

(btw, forgive my terrible english, thx)

Upvotes: 13

Views: 8647

Answers (2)

A-S
A-S

Reputation: 3125

This now also works, and much nicer and readable:

type T_Platforms = Partial<Record<T_PlatformKey, T_PlatformInfo>>;

Playground

Upvotes: 20

Aleksey L.
Aleksey L.

Reputation: 37918

You can use mapped type (similar to Record implementation) and specify that each key is optional:

type T_Platforms = { [Key in T_PlatformKey]?: T_PlatformInfo }

Playground

Upvotes: 14

Related Questions