Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 410
Rains-episode Avatar asked Dec 21 '25 15:12

Rains-episode


1 Answers

This now also works, and much nicer and readable:

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

Playground

like image 133
A-S Avatar answered Dec 24 '25 11:12

A-S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!