Skip to content

Instantly share code, notes, and snippets.

@Luisgustavom1
Last active July 31, 2022 16:36
Show Gist options
  • Save Luisgustavom1/ccb4db4ea76318ca512096eefae156d4 to your computer and use it in GitHub Desktop.
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
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