How to Write Clean TypeScript Code | by Tomoe Li | Mar, 2022

How to Write Clean TypeScript Code | Tomoe Li
Picture by Olia Gozha on Unsplash
const obj = 
elementId: '#dashboard',
// Attempt modifying the properties of ElementID
obj.elementId = '';
// output => ''
console.log(obj.elementId)
TypeScript as const keyword | Tomoe Li
TypeScript as const key phrase
operate loadPages(rely?: quantity) 
const loadCount = rely !== undefined ? rely : 10;
// ...
operate loadPages(rely: quantity = 10) 
// ...
const IMPORT_FILE_ERROR_MESSAGE: File<ImportFileErrorType, string> =   
'LIMIT': 'import.file.restrict',
'UPLOAD_FAILED': 'import.file.add.failed'
export enum ImportFileErrorType 
LIMIT = 'LIMIT',
UPLOAD_FAILED = 'UPLOAD_FAILED',
const IMPORT_FILE_ERROR_MESSAGE: File<ImportFileErrorType, string> =
[ImportFileErrorType.LIMIT]: 'import.file.restrict',
[ImportFileErrorType.UPLOAD_FAILED]: 'import.file.add.failed'
class Animal 
a(): void
class Canine extends Animal // No error, however the Animal is the bottom class,
// We do not need it to be instantiated
new Animal().a()
summary class Animal 
a(): void
class Canine extends Animal
a()
// Error: Can not create an occasion of an summary class.(2511)
new Animal().a()
class UserManager 
// Unhealthy: every non-public variable is utilized by one or one other group of strategies.
// It makes clear proof that the category is holding greater than a single duty.
// If I would like solely to create the service to get the transactions for a consumer,
// I am nonetheless pressured to go and occasion of `emailSender`.
constructor(
non-public readonly db: Database,
non-public readonly emailSender: EmailSender)
async getUser(id: quantity): Promise<Person>
return await db.customers.findOne( id );
async getTransactions(userId: quantity): Promise<Transaction[]>
return await db.transactions.discover( userId );
async sendGreeting(): Promise<void>
await emailSender.ship('Welcome!');
async sendNotification(textual content: string): Promise<void>
await emailSender.ship(textual content);
async sendNewsletter(): Promise<void>
// ...

class UserService 
constructor(non-public readonly db: Database)
async getUser(id: quantity): Promise<Person>
return await this.db.customers.findOne( id );
async getTransactions(userId: quantity): Promise<Transaction[]>
return await this.db.transactions.discover( userId );

class UserNotifier
constructor(non-public readonly emailSender: EmailSender)
async sendGreeting(): Promise<void>
await this.emailSender.ship('Welcome!');
async sendNotification(textual content: string): Promise<void>
await this.emailSender.ship(textual content);
async sendNewsletter(): Promise<void>
// ...

  1. Your inheritance represents an “is-a” relationship and never a “has-a” relationship (Human->Animal vs. Person->UserDetails).
  2. You possibly can reuse code from the bottom courses (People can transfer like all animals).
  3. You need to make international modifications to derived courses by altering a base class. (Change the caloric expenditure of all animals once they transfer).
class Worker 
constructor(
non-public readonly title: string,
non-public readonly electronic mail: string)
// ...
// Unhealthy as a result of Workers "have" tax knowledge.
// EmployeeTaxData just isn't a kind of Worker
class EmployeeTaxData extends Worker
constructor(
title: string,
electronic mail: string,
non-public readonly ssn: string,
non-public readonly wage: quantity)
tremendous(title, electronic mail);
// ...
class Worker 
non-public taxData: EmployeeTaxData;
constructor(
non-public readonly title: string,
non-public readonly electronic mail: string)
setTaxData(ssn: string, wage: quantity): Worker
this.taxData = new EmployeeTaxData(ssn, wage);
return this;
// ...
class EmployeeTaxData
constructor(
public readonly ssn: string,
public readonly wage: quantity)
// ...
const getUserNameById = (id: string) => 
interface IUser 
readonly id: string;
title: string;
electronic mail: string;
const getUserNameById = (id: IUser['id']) =>
const isCurrentUser = (consumer: IUser): consumer is IUser =>  
return consumer.title === 'Keris'

More Posts