Created
February 8, 2020 18:44
-
-
Save arianacosta/d1902fc8debc3e81c5db69b1342181fe to your computer and use it in GitHub Desktop.
Data Transfer Object for the User type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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