Types
Note: Interfaces should be used to describe objects in most cases, but occasionally using types may be needed.
Basic Usage
const engineConfig: string = 'I6';
const horsepower: number = 320;
const isForSale: boolean = false;
const salesData: any = null;
Primitive Types
type EngineConfig = string;
type Horsepower = number;
type IsForSale = boolean;
type SalesData = any; // try to avoid using this as it is loose typing
type ListForSaleFn = (price: number) => void; // void does not return a value
type ThrowSaleError = (msg: string): never { // never represents a function terminating type
throw new Error(msg);
}
Generic Types
type PaintColors = Array<string>;
type ModelYears = Array<number>;
Common Type Examples
The below Car object has properties with common type examples.
type Car {
engineConfig?: string; // ? = optional, could be EV
horsepower: number; // required, all cars have this measurement
isForSale?: boolean;
listForSale?: (price: number) => void;
[key: string]: string; // accepts any index
readonly id: string; // readonly
}
Union Types
type EngineConfig = 'I3' | 'I4' | 'I5' | 'I6' | 'V6' | 'V8' | 'V10' | 'V12';
Object Literal Type
type ManufacturerInfo = {
make: string;
model: string;
};
Intersection Types
Similar to how an interface extends another, this will merge the types.
type CarWithMakeModel = Car & ManufacturerInfo;
// Usage
const modelSupra: CarWithMakeModel = {
engineConfig: 'I6',
horsepower: 320,
make: 'Toyota',
model: 'Supra'
}
Tuple Types
Special-cased array with known types at specific indexes.
type CarTuple = [make: string, model: string, horsepower: number, engineConfig: string];
const supraModel: CarTuple = ['Toyota', 'Supra', 320, 'I6'];
const supraModel: CarTuple = ['Toyota', 320, 'Supra', 'I6']; // ERROR
Interfaces
Used to define the shape of objects. Can be extended as a way to share similar chunks of properties.
type EngineConfig = 'I3' | 'I4' | 'I5' | 'I6' | 'V6' | 'V8' | 'V10' | 'V12';
interface ManufacturerInfo {
make: string;
model: string;
}
interface Car extends ManufacturerInfo {
engineConfig: EngineConfig;
horsepower: number;
isForSale?: boolean;
listForSale?: (price: number) => void;
}
// Usage
const modelSupra: Car = {
engineConfig: 'I6',
horsepower: 320,
manufacturer: 'Toyota',
model: 'Supra'
}
Arrays
Basic Usage
const numbersArray: Array<number> = [1,2,3];
// OR
const numbersArray: number[] = [1,2,3];
Functions
Basic Examples
const checkIsCarSold = (id: listingId): boolean => {
return soldListingIds.includes(id);
}
// Promise
async function getSalesData(id: string): Promise<any> {
return ebayApi.getData(id);
}
// Generic
function getFirstSale<Sale>(sales: Sale[]) {
return sales[0];
}
// Optional Parameters
function getCarsData(make?: string, model?: string) {
// ...
}
// With Union Type
const listCarsForSaleById = (id: number | string) => {
if (typeof id === 'number')
return carsByNumberId(id);
else
return carsById(id);
}
Modules
TypeScript extends ES6 modules by adding type to import and export.
// filename: ModificationTypes.ts
export type EngineMods = { exhaustType: string, intakeType: string };
export type ExteriorMods = { aeroLevel: number, wheelType: string };
// Usage
import type { EngineMods, ExteriorMods } from './ModificationTypes.ts';
export type VehicleModifications = EngineMods | ExteriorMods;
Classes
Classes are another way to extend types, but seemingly less used than interfaces for most web projects.
interface CarModel {
make: string;
model: string;
}
class Car {
make: string;
model: string;
constructor(make: string, model: string) {
this.make = make;
this.model = model;
}
}
// Usage
const supraModel: CarModel = new Car('Toyota', 'Supra');
Glossary
A glossary of terms.
| Term | Definition |
|---|---|
| JSX | Embeddable XML-like syntax supported by TypeScript to be used directly within TypeScript, as long as the file has a .tsx extension |
| Modules | Any file containing a top-level import or export, executed within their own scope, instead of the global scope |
| Namespaces | Refers to internal modules |
| Primitives | The 3 main primitive value types are string, number, and boolean |