How do I type an object with known and unknown keys in TypeScript

前端 未结 2 1776
青春惊慌失措
青春惊慌失措 2020-12-05 07:51

I am looking for a way to create TypeScript types for the following object that has two known keys and one unknown key that has a known type:

interface Combo         


        
2条回答
  •  抹茶落季
    2020-12-05 08:19

    Nice one @jcalz

    It gave me some good insight to get where I wanted. I have like a BaseObject with some known properties and the BaseObject can have as many BaseObjects as it wants.

    type BaseObject = { known: boolean, field: number };
    type CoolType> = BaseObject & Record;
    const asComboObject = (x: C & CoolType): C => x;
    
    const tooManyExtraKeys = asComboObject({
         known: true,
         field: 123,
         unknownName: {
             known: false,
             field: 333
         },
         anAdditionalName: {
             known: true,
             field: 444
         },
    });
    

    and this way I can get type checks for the structure that I already had without changing too much.

    ty

提交回复
热议问题