Last active
July 31, 2022 16:36
-
-
Save Luisgustavom1/ccb4db4ea76318ca512096eefae156d4 to your computer and use it in GitHub Desktop.
This is a types helper based on the specific types of properties. Created in this article to practice and study https://dev.to/busypeoples/notes-on-typescript-type-level-programming-part-3-3l03
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 User = { | |
id: number, | |
name: string, | |
age: number, | |
active: boolean, | |
} | |
type FilterByType<T, U> = { | |
[K in keyof T]: T[K] extends U ? K : never | |
}[keyof T] | |
type IncludesByType<Obj, T> = Pick<Obj, FilterByType<Obj, T>> | |
type ExcludesByType<Obj, T> = Omit<Obj, FilterByType<Obj, T>> | |
type ReadOnlyByType<Obj, T> = ExcludesByType<Obj, T> & Readonly<IncludesByType<Obj, T>>; | |
type OptionalByType<Obj, T> = Partial<IncludesByType<Obj, T>> & ExcludesByType<Obj, T> | |
type RequiredByType<Obj, T> = Partial<ExcludesByType<Obj, T>> & IncludesByType<Obj, T> | |
type OnlyMakeTypeOptional<Obj, T> = Partial<IncludesByType<Obj, T>> & ExcludesByType<Obj, T> | |
type OnlyMakeTypeRequired<Obj, T> = Required<IncludesByType<Obj, T>> & ExcludesByType<Obj, T> | |
// Make a only boolean types as readonly | |
const user: ReadOnlyByType<User, boolean> = { | |
id: 1, | |
name: 'string', | |
age: 2, | |
active: true, | |
} | |
// Error!! - boolean properties in the User are readonly | |
user.active = false; | |
// Right | |
user.name = 'name' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment