how to make function like Object.keys but returning array with proper types instead of…
- User
how to make function like Object.keys but returning array with proper types instead of string[]
- Assistant
To make a function like
Object.keysthat returns an array with proper types instead ofstring[], you can use thekeyofoperator in TypeScript to get the keys of an object as a union type, and then use that union type to create an array of the same type.Here is an example of such a function:
type KeysOfType<T, U> = { [K in keyof T]: T[K] extends U ? K : never; }[keyof T]; function keysWithType<T extends object>(obj: T): KeysOfType<T, any>[] { return Object.keys(obj) as KeysOfType<T, any>[]; }In this example,
KeysOfType<T, U>is a mapped type that creates a new object type with only the keys ofTwhose values are of typeU. ThekeysWithTypefunction uses this type to cast the keys returned byObject.keysto the appropriate type.To use this function, you can pass an object to it and it will return an array of keys with the appropriate types:
const obj = { key1: 1, key2: "two", key3: true, }; const keys = keysWithType(obj); // `keys` is ["key1", "key2", "key3"] of type ("key1" | "key2" | "key3")[]