Knowing Partials in Typescript
If TypeScript were a friend of mine on Facebook, then I’d mark our relation as complicated. It’s a history of love & hate, or rather hate & appreciation. I was a TypeScript hater.
JavaScript is a Dynamic language with capabilities of being a functional language. it’s a language.
Let’s say we have a UserModel interface:
interface UserModel {
email: string;
password: string;
address: string;
phone: string;
}
And a User class with update() method:
class User {
update( user: UserModel ) {
// Update user
}
}
The problem with the code above is that we must pass an object that implements the whole UserModel interface, otherwise typescript will be 😡.
But in our case, we want to be dynamic and not be committed to the entire interface, but still get IntelliSense.
TypeScript (v2.1) provides us with a solution precisely for these cases — The Partial interface
All we need to do is to change the code above to this:
class User {
update( user: Partial<UserModel> ) {
// Update user
}
}
Another useful example would be if you have a component that takes configuration object as Input() and you want to have a default value.
type ComponentConfig = {
optionOne: string;
optionTwo: string;
optionThree: string;
}
export class SomeComponent {
private _defaultConfig: Partial<ComponentConfig> = {
optionOne: '...'
}
@Input() config: ComponentConfig;
ngOnInit() {
const merged = { ...this._defaultConfig, ...this.config };
}
}
Under the hood the Partial interface looks like this:
type Partial<T> = { [P in keyof T]?: T[P]; };