Home > front end >  How to select type of object value in array using TS
How to select type of object value in array using TS

Time:11-15

I would like to create type from key in my code:

const arr = [{ key: "a", nnumber: 11 }, { key: "b", nnumber: 1 }];

function test<Keys['key'] extends keyof string>(keys: Keys): Keys[] {
    return arr.map((item) => item.key);
}

// should return "a", "b"
const tmp = test(arr);
//   ^?

Can anyone help me to create type for return ["a", "b"].

Thank you

CodePudding user response:

Make your array a constant type with as const then you can retrive the type.

const arr = [{ key: "a", nnumber: 11 }, { key: "b", nnumber: 1 }] as const;


type foo = typeof arr[number]["key"]
  // ^? "a" | "b" 

CodePudding user response:

Your generic parameter should represent the keys:

const arr = [{ key: "a", nnumber: 11 }, { key: "b", nnumber: 1 }] as const;

function test<K extends string>(keys: readonly { key: K }[]): K[] {
    return arr.map((item) => item.key as K);
}

const tmp = test(arr);
//   ^? ("a" | "b")[]

Playground

  • Related