If I have the following type
interface Foo {
bar: string;
baz: number;
qux: string;
}
can I use typeof
to type a parameter such that it only takes keys of Foo
that return string
('bar'
or 'qux'
)?
With the addition of the as
clause in mapped types we can now simplify the original type to:
type KeyOfType<T, V> = keyof {
[P in keyof T as T[P] extends V? P: never]: any
}
You can use conditional types in Typescript 2.8 :
type KeysOfType<T, TProp> = { [P in keyof T]: T[P] extends TProp? P : never }[keyof T];
let onlyStrings: KeysOfType<Foo, string>;
onlyStrings = 'baz' // error
onlyStrings = 'bar' // ok
let onlyNumbers: KeysOfType<Foo, number>;
onlyNumbers = 'baz' // ok
onlyNumbers = 'bar' // error
KeysOfType
to include keyof T & { [P ....
or else I couldn't use a KeysOfType
to then subscript T
.
Commented
Mar 5, 2020 at 21:03
number | null
filtering properties which have number
type?
Commented
May 4, 2022 at 11:44
type TypeSafeUnion<T1, T2> = { [P in keyof (T1 | T2) as T1[P] extends T2[P] ? T2[P] extends T1[P] ? P : never : never]: (T1[P] | T2[P]); };
Commented
Oct 25, 2022 at 4:04