Skip to content

Instantly share code, notes, and snippets.

@pSapien
Last active May 28, 2022 06:04
Show Gist options
  • Save pSapien/e77828d4d1ef7d789d1f0de71297947c to your computer and use it in GitHub Desktop.
Save pSapien/e77828d4d1ef7d789d1f0de71297947c to your computer and use it in GitHub Desktop.
filtering types from an interface or type using conditionals.
type Job = {
id: string;
salary: number;
title: string;
}
interface User {
id: string;
name: string;
company: string;
position: 'internship' | 'regular';
mobileNumber: number;
gender: string;
jobs: Job[];
getAge: () => number;
}
type OnlyStringForm = {
[key in keyof User]: User[key] extends string ? key : never
}[keyof User]
type OnlyNumberString = {
[key in keyof User]: User[key] extends number ? key : never
}[keyof User]
type OnlyMethodsThatReturnNumber = {
[key in keyof User]: User[key] extends () => number ? key : never
}[keyof User]
type Filtered<ObjectType, Condition> = {
[key in keyof ObjectType]: ObjectType[key] extends Condition ? key : never
}[keyof ObjectType]
type UsingFilteredOnlyStringForm = Filtered<User, string> // "id" | "name" | "company" | "position" | "gender"
type UsingFilteredOnlyNumberForm = Filtered<User, number> // "mobileNumber"
type UsingFilteredOnlyMethodsThatReturnNumber = Filtered<User, () => number> // "getAge"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment