The following answer addresses how to safely extract property names from a type. What this answer accomplishes is that, indeed, if there is a mistyping you get a compile-time error, not a runtime error:
https://mcmap.net/q/747710/-safe-way-to-extract-property-names
However, the property names extracted in this manner are typed as string
, not as a string literal (with the name of the actual property). This has some limiting implications, e.g. it does not allow them to be used with the Omit
utility type.
This typescript playground link demonstrates the problem. Playground code pasted below for completeness purposes:
function propertyOf<T>(name: keyof T) {
return name;
}
type AB = {a: number, b: number};
const A = propertyOf<AB>('a');
/*
* Now say that I want to constuct the following type:
*
* type B = {b: number}
*
* ... with the qualification that I want to construct it by omitting
* some properties from a wider type. `A` cannot be used for this
* purpose so one has to again type the name of the property as: 'a'
*
*/
type B_by_omit = Omit<AB, 'a'> // type of B_by_omit is correctly pronounced as {b: number}
type B_by_omit2 = Omit<AB, typeof A> // type of B_by_omit2 is {}
Is there way to safely extract property names from a type and have them typed as string literals?