You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Item 72: Prefer ECMAScript Features to TypeScript Features
Things to Remember
By and large, you can convert TypeScript to JavaScript by removing all the types from your code.
Enums, parameter properties, triple-slash imports, experimental decorators, and member visibility modifiers are historical exceptions to this rule.
To keep TypeScript’s role in your codebase as clear as possible and to avoid future compatibility issues, avoid nonstandard features.
Code Samples
enumFlavor{Vanilla=0,Chocolate=1,Strawberry=2,}letflavor=Flavor.Chocolate;// ^? let flavor: FlavorFlavor// Autocomplete shows: Vanilla, Chocolate, StrawberryFlavor[0]// Value is "Vanilla"
enumFlavor{Vanilla='vanilla',Chocolate='chocolate',Strawberry='strawberry',}letfavoriteFlavor=Flavor.Chocolate;// Type is FlavorfavoriteFlavor='strawberry';// ~~~~~~~~~~~ Type '"strawberry"' is not assignable to type 'Flavor'
typeFlavor='vanilla'|'chocolate'|'strawberry';letfavoriteFlavor: Flavor='chocolate';// OKfavoriteFlavor='americone dream';// ~~~~~~~~~~~ Type '"americone dream"' is not assignable to type 'Flavor'
classDiary{privatesecret='cheated on my English test';}constdiary=newDiary();diary.secret// ~~~~~~ Property 'secret' is private and only accessible within ... 'Diary'
classPasswordChecker{
#passwordHash: number;constructor(passwordHash: number){this.#passwordHash =passwordHash;}checkPassword(password: string){returnhash(password)===this.#passwordHash;}}constchecker=newPasswordChecker(hash('s3cret'));checker.#passwordHash
// ~~~~~~~~~~~~~ Property '#passwordHash' is not accessible outside class// 'PasswordChecker' because it has a private identifier.checker.checkPassword('secret');// Returns falsechecker.checkPassword('s3cret');// Returns true