TypeScript Introduction
3/15/24About 3 min
TypeScript Introduction
Overview
TypeScript is a superset of JavaScript that adds a type system and other features. This article introduces the core concepts and usage of TypeScript.
1. Installation and Configuration
1.1 Installing TypeScript
# Global install
npm install -g typescript
# Project install
npm install typescript --save-dev
# Initialize config
tsc --init1.2 tsconfig.json Configuration
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"],
"exclude": ["node_modules"]
}2. Basic Types
2.1 Primitive Types
// String
let name: string = 'Blogger'
// Number
let age: number = 30
// Boolean
let isActive: boolean = true
// Array
let numbers: number[] = [1, 2, 3]
let strings: Array<string> = ['a', 'b', 'c']
// Tuple
let tuple: [string, number] = ['hello', 10]
// Enum
enum Color {
Red,
Green,
Blue
}
let color: Color = Color.Green
// Any type
let anyValue: any = 'hello'
anyValue = 123
// Void type
let nothing: void = undefined
// Never returns
function throwError(): never {
throw new Error('Error')
}2.2 Type Inference
// TypeScript automatically infers types
let message = 'Hello' // inferred as string
let count = 42 // inferred as number
let isDone = false // inferred as boolean3. Interfaces
3.1 Basic Interface
interface User {
id: number
name: string
age?: number // optional property
readonly email: string // readonly property
}
const user: User = {
id: 1,
name: 'Blogger',
email: 'user@example.com'
}
// Type assertion
const anotherUser = {} as User
anotherUser.id = 23.2 Interface Inheritance
interface Person {
name: string
age: number
}
interface Employee extends Person {
employeeId: number
department: string
}
const employee: Employee = {
name: 'Blogger',
age: 30,
employeeId: 1001,
department: '技术部'
}3.3 Function Interface
interface SearchFunc {
(source: string, subString: string): boolean
}
const search: SearchFunc = (source, subString) => {
return source.includes(subString)
}4. Classes
4.1 Basic Class
class Person {
// Properties
name: string
private age: number // private property
protected gender: string // protected property
// Constructor
constructor(name: string, age: number, gender: string) {
this.name = name
this.age = age
this.gender = gender
}
// Method
greet(): string {
return `Hello, my name is ${this.name}`
}
// Getter
getAge(): number {
return this.age
}
// Setter
setAge(newAge: number): void {
if (newAge > 0) {
this.age = newAge
}
}
}
// Instantiate
const person = new Person('Blogger', 30, '男')
console.log(person.greet())4.2 Class Inheritance
class Employee extends Person {
employeeId: number
constructor(name: string, age: number, gender: string, employeeId: number) {
super(name, age, gender) // call parent constructor
this.employeeId = employeeId
}
work(): string {
return `${this.name} is working`
}
}
const employee = new Employee('Blogger', 30, '男', 1001)
console.log(employee.work())4.3 Abstract Class
abstract class Animal {
abstract makeSound(): void
move(): void {
console.log('Moving...')
}
}
class Dog extends Animal {
makeSound(): void {
console.log('Woof!')
}
}
const dog = new Dog()
dog.makeSound() // Woof!
dog.move() // Moving...5. Generics
5.1 Generic Functions
function identity<T>(arg: T): T {
return arg
}
// Usage
const num = identity<number>(42)
const str = identity<string>('hello')
const arr = identity<number[]>([1, 2, 3])5.2 Generic Classes
class GenericNumber<T> {
zeroValue: T
add: (x: T, y: T) => T
constructor(zeroValue: T, addFn: (x: T, y: T) => T) {
this.zeroValue = zeroValue
this.add = addFn
}
}
const myNumber = new GenericNumber<number>(0, (x, y) => x + y)
console.log(myNumber.add(5, 3)) // 85.3 Generic Constraints
interface Lengthwise {
length: number
}
function logLength<T extends Lengthwise>(arg: T): T {
console.log(arg.length)
return arg
}
logLength('hello') // 5
logLength([1, 2, 3]) // 3
logLength({ length: 10, value: 'test' }) // 106. Type Guards
6.1 typeof Type Guard
function printValue(value: string | number) {
if (typeof value === 'string') {
console.log(value.toUpperCase())
} else {
console.log(value.toFixed(2))
}
}6.2 instanceof Type Guard
class Bird {
fly() { console.log('Flying') }
}
class Fish {
swim() { console.log('Swimming') }
}
function move(animal: Bird | Fish) {
if (animal instanceof Bird) {
animal.fly()
} else {
animal.swim()
}
}6.3 Custom Type Guard
interface Dog {
bark(): void
}
interface Cat {
meow(): void
}
function isDog(pet: Dog | Cat): pet is Dog {
return (pet as Dog).bark !== undefined
}
function speak(pet: Dog | Cat) {
if (isDog(pet)) {
pet.bark()
} else {
pet.meow()
}
}7. Modules and Namespaces
7.1 Module Import and Export
// utils.ts
export function add(a: number, b: number): number {
return a + b
}
export const PI = 3.14159
export interface Point {
x: number
y: number
}
// main.ts
import { add, PI, Point } from './utils'
console.log(add(2, 3)) // 5
console.log(PI) // 3.14159
const point: Point = { x: 10, y: 20 }7.2 Default Export
// calculator.ts
export default class Calculator {
add(a: number, b: number): number {
return a + b
}
}
// main.ts
import Calculator from './calculator'
const calc = new Calculator()
console.log(calc.add(2, 3)) // 58. Utility Types
8.1 Partial
interface User {
id: number
name: string
email: string
}
// All properties become optional
type PartialUser = Partial<User>
// { id?: number; name?: string; email?: string }8.2 Readonly
type ReadonlyUser = Readonly<User>
// { readonly id: number; readonly name: string; readonly email: string }8.3 Pick
type UserName = Pick<User, 'name' | 'email'>
// { name: string; email: string }8.4 Omit
type UserWithoutId = Omit<User, 'id'>
// { name: string; email: string }8.5 Record
type UserRecord = Record<string, User>
// { [key: string]: User }Summary
TypeScript provides a powerful type system that helps developers catch errors at compile time, improving code quality and development efficiency.
Author: Lei Tao
Date: March 15, 2024