Skip to content

Instantly share code, notes, and snippets.

@mikaelvesavuori
Created October 30, 2022 14:35
Show Gist options
  • Save mikaelvesavuori/cd2b21941b7107ab3f61d2891edb4d2c to your computer and use it in GitHub Desktop.
Save mikaelvesavuori/cd2b21941b7107ab3f61d2891edb4d2c to your computer and use it in GitHub Desktop.
TypeScript utility type demos.
type Dog = {
name: string;
race: RacesLimitedList;
};
type RacesFullList = 'Alsatian' | 'Pomeranian';
type RacesLimitedList = Exclude<RacesFullList, 'Pomeranian'>;
const dog: Dog = {
name: 'Sam',
race: 'Pomeranian'
};
console.log(dog);
export { };
type LivingBeing = {
name: string;
race: string;
};
// Omit only 'race' property from whichever number of properties that LivingBeing has
type Person = {
[Property in keyof Omit<LivingBeing, 'race'>]: string;
};
const person: Person = {
name: 'Sam'
};
console.log(person);
export { };
type Dog = {
name: string;
race: string;
};
function makeDog(name: string, race: string): Dog {
return {
name,
race
};
}
// This will contain the parameters from the `makeDog()` function
type DogParams = Parameters<typeof makeDog>;
export { };
type LivingBeing<> = {
name: string;
race: string;
};
// Make all properties partial
type Person = Partial<LivingBeing>;
const person: Person = {};
console.log(person);
export { };
type Dog = {
name: string;
race: string;
};
// Pick out only 'name' as required property
type Person = Pick<Dog, 'name'>;
const person: Person = {
name: 'Sam'
};
console.log(person);
export { };
type LivingBeing<T> = {
[P in keyof T]-?: T[P];
};
type Person = {
name: string;
};
type Dog = Required<Person> & {
race: string;
};
const dog: LivingBeing<Dog> = {
name: 'Sam',
race: 'Alsatian'
};
console.log(dog);
export { };
type Dog = {
name: string;
race: string;
};
function makeDog() {
return {
name: 'Sam',
race: 'Alsatian',
city: 'Someville'
};
}
// This will contain the return type from the `makeDog()` function
type DogReturnType = ReturnType<typeof makeDog>;
export { };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment