Last active
March 7, 2018 19:04
-
-
Save cwilper/555b1200d4707df93c205628371a8fbf to your computer and use it in GitHub Desktop.
Typescript example: Constructor with optional args via interface.
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
// 1. Define an interface for the optional args to your constructor. | |
interface PersonArgs { | |
nickname?: string; | |
age?: number; | |
} | |
class Person { | |
// 2. Add the args as the last parameter of the constructor, with a default value of {}. | |
constructor(private _name: string, private _args: PersonArgs = {}) { | |
} | |
/** Gets the name. */ | |
get name(): string { | |
return this._name; | |
} | |
/** Gets the age, or undefined if not known. */ | |
get age(): number | undefined { | |
return this._args.age; | |
} | |
/** Gets the nickname, or a default one. */ | |
get nickname(): string { | |
return this._args.nickname || "Hey you"; | |
} | |
/** Demonstrates use of getters. */ | |
describe() { | |
alert("Given name: " + this.name + "\n" | |
+ "Nickname: " + this.nickname + "\n" | |
+ "Age:" + (this.age || "Unknown")); | |
} | |
} | |
// 3. Create instances with known optionals given as an object. | |
new Person("Robert", { nickname: "Bob", age: 2 }).describe(); | |
new Person("Sharon", { age: 42 }).describe(); | |
new Person("Elmo").describe(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment