The compiler infers the type of the list
in your example to be Array<{name: string}>
. This means that the particular string literal types of the name
properties are forgotten by the time you define Title
.
To address this, you need to adjust how you assign values to list
. One way to do this is to use a const
assertion, which instructs the compiler to infer the narrowest possible type:
export const list = [
{ name: 'parentTitle', },
{ name: 'anotherTitle', },
{ name: 'whatever', },
] as const;
Now, list
is inferred to have the following type:
/*
const list: readonly [
{ readonly name: "parentTitle";},
{ readonly name: "anotherTitle";},
{ readonly name: "whatever";}
]
*/
This represents a readonly tuple of readonly objects with specific name
properties in a specified order. With this information, we can utilize lookup types to define Title
:
type Title = typeof list[number]["name"];
// type Title = "parentTitle" | "anotherTitle" | "whatever"
That should provide some clarity on resolving the issue. Good luck!
Link to Playground for code