Home > Net >  Typescript interface problem: how to get the type like t when we have a const like list
Typescript interface problem: how to get the type like t when we have a const like list

Time:03-11

const list = [
  {
    label: "phone",
    defaultValue: "1203981209",
  },
  {
    label: "isMan",
    defaultValue: false,
  },
  {
    label: "age",
    defaultValue: 22,
  },
];

type t = {
  phone: string;
  isMan: boolean;
  age: number;
};

We have list.And how to get t in Typescript. I tried to write something like type t = {[k in typeof list[number]["label"]]: typeof list[number]["defaultValue"];};,but that does not work.

CodePudding user response:

The original object needs to be typed well for this to work - since you want the literal label values for the keys in the new object, they need to be as const so they don't get widened to string. (I don't see a nice way to use as const over the whole object, because then the values don't get widened - if you went that route, you'd have to have a helper type to turn, eg, "1203981209" into string and so on).

const l = [
  {
    label: "phone" as const,
    defaultValue: "1203981209",
  },
  {
    label: "isMan" as const,
    defaultValue: false,
  },
  {
    label: "age" as const,
    defaultValue: 22,
  },
];
type T = {
    [Prop in typeof l[number] as Prop["label"]]: Prop["defaultValue"];
};

CodePudding user response:

I would have recommended going the other way, if your use case allows, with something like

interface PropertyDefaultValue<K extends keyof t = keyof t> {
  label: K;
  defaultValue: t[K];
}

const list: PropertyDefaultValue[] = ....

That said, while I was writing this, @CertainPerformace posted their answer and I think I like theirs better than mine in many use cases.

That said, mine doesn't require that all default properties be defined.

Also, are you sure this is the way you want to go? I've always defined an object with my default values, then fleshed out my objects using myFilledObj = Object.assign({}, myDefaultObj, mySpecificObjBeforeFillingDefaultValues)

  • Related