Skip to content

Instantly share code, notes, and snippets.

@cwilper
Last active March 7, 2018 19:04
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 cwilper/555b1200d4707df93c205628371a8fbf to your computer and use it in GitHub Desktop.
Save cwilper/555b1200d4707df93c205628371a8fbf to your computer and use it in GitHub Desktop.
Typescript example: Constructor with optional args via interface.
// 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