41

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')?

1 Answer 1

82

Typescript 4.1 and above

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
}

Playground Link

Original answer

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 

Playground Link

9
  • 2
    Thanks for this answer. in my using it, I found I needed to extend KeysOfType to include keyof T & { [P .... or else I couldn't use a KeysOfType to then subscript T.
    – Rob Napier
    Commented Mar 5, 2020 at 21:03
  • How to make it to respect nullable column like number | null filtering properties which have number type? Commented May 4, 2022 at 11:44
  • Link to docs of 'as' clause.
    – user764754
    Commented Sep 7, 2022 at 14:06
  • Thank you! This was exactly what I was looking for - now I was able to write: 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]); };
    – AnorZaken
    Commented Oct 25, 2022 at 4:04
  • 1
    @VadimOvchinnikov, I was wondering the same... it seems we can do something like ``` type KeyOfTypeOptionalIncluded<T, Condition> = KeyOfType<T, Condition | undefined>``` for optional keys or even ``` type KeyOfTypeNullIncluded<T, Condition> = KeyOfType<T, Condition | null>``` for the example you mentioned.... or even ``` type KeyOfTypeNullIablencluded<T, Condition> = KeyOfType<T, Condition | null | undefined>``` for optional nullable types
    – awdk
    Commented Nov 1, 2022 at 5:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.