Last active
May 28, 2022 06:04
-
-
Save pSapien/e77828d4d1ef7d789d1f0de71297947c to your computer and use it in GitHub Desktop.
filtering types from an interface or type using conditionals.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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