Skip to content

Instantly share code, notes, and snippets.

@arianacosta
Created February 8, 2020 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arianacosta/d1902fc8debc3e81c5db69b1342181fe to your computer and use it in GitHub Desktop.
Save arianacosta/d1902fc8debc3e81c5db69b1342181fe to your computer and use it in GitHub Desktop.
Data Transfer Object for the User type
export class UserDto {
static from(input: unknown) {
const parsedInput = typeof input === 'string' ? JSON.parse(input) : input;
if(!UserDto.isValid(parsedInput)) {
throw Error('Invalid input type');
}
// at this point `parsedInput` is guaranteed to match `UserDto`
const { firstName, lastName, isFormal } = parsedInput;
return new UserDto(firstName, lastName, isFormal);
}
// note the use of `is` to type guard to `UserDto`
protected static isValid(input: any) : input is UserDto {
return (
typeof input.firstName === 'string' &&
typeof input.lastName === 'string' &&
typeof input.isFormal === 'boolean'
);
}
constructor(
readonly firstName: string,
readonly lastName: string,
readonly isFormal: boolean
) { }
serialize() {
return JSON.stringify(this);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment