Open genkio opened 5 years ago
class User { static readonly minimumNameLength: number = 4; constructor(private _name: string, private readonly email: string) { User.assertValidName(_name); } static assertValidName(name) { const nameIsValid = name.length >= User.minimumNameLength; if (!nameIsValid) { throw Error("The given name is not valid"); } } get name(): string { return this._name; } set name(newName: string) { User.assertValidName(newName); this._name = newName; } speak() { console.log(`I am ${this.name}!!!`); } }
class Foo { x: number; constructor(x:number) { this.x = x; } } // equivalent class Foo { constructor(public x:number) { } } // one step further class ParamPropContact { constructor( public name: string, public email: string = "no email") {} } }
class Foo { members = []; // Initialize directly add(x) { this.members.push(x); } }
function arrayToDict<T extends { id: string }>(array: T[]): { [k: string]: T} { const out: { [k: string]: T } = {}; array.forEach(val => { // extends { id: string } is telling ts T has a key as id out[val.id] = val; }); return out; } // improve function arrayToDict(array: ({ id: string })[]): { [k: string]: { id: string }} { const out: { [k: string]: T } = {}; array.forEach(val => { // extends { id: string } is telling ts T has a key as id out[val.id] = val; }); return out; }
interface CommunicationMethods { email: HasEmail; phone: HasPhone; fax: { fax: number }; } function contact<K extends keyof CommunicationMethods>( method: K, contact: CommunicationMethods[K] ) { //.... } contact("email", { // only HasEmail appliance value is allowed })
type AllCommunicationMethods = keyof CommunicationMethods; type AllCommunicationValues = CommunicationMethods[keyof CommunicationMethods];
type ResolveType = typeof Promise.resolve;
readonly
Simple class example
Constructor shorthand
Property initializer (ES7)
Understanding generics
Adding constraints to type parameters
Matching key to value using extends keyof
Creating new types with keys or values of another type
Using typeof to create your own type base on other's type
Use
readonly
to prevent errors from mutating objectsPrefer function expressions over function declarations for type reusability
Prefer unknown over any to get better type safety
Lean into JSDoc or TSDoc style comments for better development experience