0

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

2 Answers 2

1

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" 
Sign up to request clarification or add additional context in comments.

1 Comment

It is possible to implement this type into my function? For getting union/array of arr value?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.