Skip to content

Instantly share code, notes, and snippets.

@gvergnaud
Last active June 27, 2021 15:59
Show Gist options
  • Save gvergnaud/650a6f52c098a09a0eb5a2d9b7dfe9d4 to your computer and use it in GitHub Desktop.
Save gvergnaud/650a6f52c098a09a0eb5a2d9b7dfe9d4 to your computer and use it in GitHub Desktop.
Assigning properties to an Object type in TypeScript
/**
* # Assigning properties to an object type in TypeScript
*
* When we want to assign some properties on a object type
* we usually use the `&` operator:
*
* type B = A & { someProperty: string }
*
* It seems to work at first sight, but it doesn't behave exactly
* as we would expect when we try to override properties that already
* exist on type `A`. In other words it isn’t equivalent to Object.assign.
*
* With `A & B`, properties of A aren’t overrided, but instead `&`
* is also applied between each property of same key. let's see an example:
**/
type X = { prop: number }
type Y = X & { prop: string }
// you would expect Y[‘prop’] to be of type `string`, but it isn’t,
// it is of type `number & string` which evaluates to `never`:
const y: Y = {
prop: 'hello' // Typecheck Error! can’t assign string to never.
}
// Here is how to achieve assignment in TypeScript:
type Assign<A, B> = Omit<A, keyof B> & B;
// We first removes all properties of type B from the type A
// And then apply `& B` :)
type A = { prop: number, anotherProp: number }
type B = Assign<A, { prop: string }>
const b: B = {
prop: 'hello', // it works!
anotherProp: 10
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment