I am attempting to write the specifications for a function that can take records of any structure and convert the values into a discriminated union. For example:
const getKeys = <T extends {key: string}>(items: T[]): T['key'] => {
// ...
}
// keys should have type "foo" | "bar"
// but currently has type string
const keys = getKeys([{ key: "foo" }, { key: "bar" }])
// keys2 should have type "baz" | "qux"
// but currently has type string
const keys2 = getKeys([{ key: "foo" }, { key: "qux" }])
Unfortunately, keys
and keys2
are being assigned the type of string
instead.
My goal is to achieve a similar API as shown in the following working example, but using records:
const getKeys = <T extends string>(items: T[]): T => {
// ...
}
// keys has type "foo" | "bar"
const keys = getKeys(["foo", "bar"])
// keys2 has type "baz" | "qux"
const keys2 = getKeys(["baz", "qux"])
Is there a way to achieve this?
Requirements
- Usage of
as const
on the argument must be avoided