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.
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"];
};