Have been given a typed object
type TestObj = {
one: "up";
two: "down";
three: "left";
four: "right";
}
Of which I have to choose 0 or more keys from and turn into an array
type TestObjKeys = keyof TestObj;
const chosen: TestObjKeys[] = ["one", "four"];
I need to convert this into a new typescript obj for only the keys that were chosen
type NewTestObj = Pick<TestObj, (typeof chosen)[number]>;
However the above gives me a type (equivalent to TestObj) for all keys, rather than use "one" and "four". I tried turning it into a const
const chosen2 = chosen as const;
But it errors out with
A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.(1355)
How can I get only the chosen keys?
2
Answers
(typeof chosen)[number]
is justTestObjKeys
not chosen keys.If you add
as const
assertion to chosen directly, without the explicit type it would work.If you still need explicit type i recommend using the
satisfies
operator.You need to:
chosen
, so TypeScript can infer it. (You could usesatisfies
to make sure it satisfies a type, though, if you wanted.)and
as const
on the array you’re assigning tochosen
, so TypeScript knows it’s a tuple of string literal types, not an array of string.Like this:
Playground link
(There’s also no need for the
()
aroundtypeof chosen
, it has higher precedence [if that’s the word] than the[number]
after it. Justtypeof chosen[number]
will do the job.)