基础的类型校验
函数输入参数校验
function greet(name: string) {
console.log("Hello, " + name.toUpperCase() + "!!");
}
greet('43');
function printCoord(pt: { x: number; y: number }) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord({ x: 3, y: 7 });
function printName(obj: { first: string; last?: string }) {
}
function printId(id: number | string) {
console.log("Your ID is: " + id);
}
type Point = {
x: number;
y: number;
};
function printCoord2(pt: Point) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord2({ x: 100, y: 100 });
interface Point2 {
x: number;
y: number;
}
function printCoord3(pt: Point2) {
console.log("The coordinate's x value is " + pt.x);
console.log("The coordinate's y value is " + pt.y);
}
printCoord3({ x: 100, y: 100 });
const myCanvas = <HTMLCanvasElement>document.getElementById("main_canvas");
function printText(s: string, alignment: "left" | "right" | "center") {
}
printText("Hello, world", "left");
函数返回值校验
function getFavoriteNumber(): number {
return 26;
}
类的继承
interface Pingable {
ping(): void;
}
class Sonar implements Pingable {
ping() {
console.log("ping!");
}
}
declare resident: Dog;
函数
输入参数为函数时的类型校验
function greeter(fn: (a: string) => void) {
fn("Hello, World");
}
type GreetFunction = (a: string) => void;
function greeter1(fn: GreetFunction) {
}
type DescribableFunction = {
description: string;
(someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
console.log(fn.description + " returned " + fn(6));
}
type SomeObject = {}
type SomeConstructor = {
new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
return new ctor("hello");
}
泛型函数
function firstElement<Type>(arr: Type[]): Type | undefined {
return arr[0];
}
function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] {
return arr.map(func);
}
const parsed = map(["1", "2", "3"], (n) => parseInt(n));
约束
function longest<Type extends { length: number }>(a: Type, b: Type) {
if (a.length >= b.length) {
return a;
} else {
return b;
}
}
function combine<Type>(arr1: Type[], arr2: Type[]): Type[] {
return arr1.concat(arr2);
}
const arr = combine<string | number>([1, 2, 3], ["hello"]);
function f(x?: number) {
}
f();
f(10);
模块
ES 模块
export type Cat = { breed: string; yearOfBirth: number };
export interface Dog {
breeds: string[];
yearOfBirth: number;
}
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;
CommonJS 模块
import type { Cat1, Dog2 } from "./animal.js";
function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
module.exports = {
pi: 3.14,
squareTwo: 1.41,
phi: 1.61,
absolute,
};
const maths = require("maths");
maths.pi;
对象
基础的Object类型校验
interface PaintOptions {
shape: String;
xPos?: number;
yPos?: number;
}
interface SomeType {
readonly prop: string;
}
function doSomething(obj: SomeType) {
console.log(`prop has the value '${obj.prop}'.`);
obj.prop = "hello";
}
interface StringArray {
[index: number]: string;
}
扩展的Object类型校验
interface BasicAddress {
name?: string;
street: string;
city: string;
country: string;
postalCode: string;
}
interface AddressWithUnit extends BasicAddress {
unit: string;
}
interface Colorful {
color: string;
}
interface Circle {
radius: number;
}
type ColorfulCircle = Colorful & Circle;
interface Box<Type> {
contents: Type;
}
let box: Box<string>;
function doSomething1(value: Array<string>) {
}
let myArray1: string[] = ["hello", "world"];
doSomething1(myArray1);
doSomething1(new Array("hello", "world"));
type StringNumberPair = [string, number];
function doSomething2(pair: StringNumberPair) {
const a = pair[0];
const b = pair[1];
}
doSomething2(["hello", 42]);
function doSomething3(pair: readonly [string, number]) {
}
Type
泛型 Types
function identity<Type>(arg: Type): Type {
return arg;
}
let myIdentity: <Type>(arg: Type) => Type = identity;
interface Lengthwise {
length: number;
}
function loggingIdentity<Type extends Lengthwise>(arg: Type): Type {
console.log(arg.length);
return arg;
}
function getProperty<Type, Key extends keyof Type>(obj: Type, key: Key) {
return obj[key];
}
let x = { a: 1, b: 2, c: 3, d: 4 };
getProperty(x, "a");
getProperty(x, "m");
type Point = { x: number; y: number };
type P = keyof Point;
let s = "hello";
let n: typeof s;
type Person = { age: number; name: string; alive: boolean };
type Age = Person["age"];
type I1 = Person["age" | "name"];
type I2 = Person[keyof Person];
type AliveOrName = "alive" | "name";
type I3 = Person[AliveOrName];
条件 Types
- SomeType extends OtherType ? TrueType : FalseType;
interface Animal {
live(): void;
}
interface Dog extends Animal {
woof(): void;
}
type Example1 = Dog extends Animal ? number : string;
type MessageOf<T> = T extends { message: unknown } ? T["message"] : never;
interface Email {
message: string;
}
interface Dog {
bark(): void;
}
type EmailMessageContents = MessageOf<Email>;
type DogMessageContents = MessageOf<Dog>;
- Inferring Within Conditional Types
type GetReturnType<Type> = Type extends (...args: never[]) => infer Return
? Return
: never;
type Num = GetReturnType<() => number>;
type Str = GetReturnType<(x: string) => string>;
type Bools = GetReturnType<(a: boolean, b: boolean) => boolean[]>;
- Distributive Conditional Types
type ToArrayNonDist<Type> = [Type] extends [any] ? Type[] : never;
type StrArrOrNumArr = ToArrayNonDist<string | number>;
Map Types
type CreateMutable<Type> = {
-readonly [Property in keyof Type]: Type[Property];
};
type LockedAccount = {
readonly id: string;
readonly name: string;
};
type UnlockedAccount = CreateMutable<LockedAccount>;
type Concrete<Type> = {
[Property in keyof Type]-?: Type[Property];
};
type MaybeUser = {
id: string;
name?: string;
age?: number;
};
type User = Concrete<MaybeUser>;
type MappedTypeWithNewProperties<Type> = {
[Properties in keyof Type as NewKeyType]: Type[Properties]
}
type Getters<Type> = {
[Property in keyof Type as `get${Capitalize<string & Property>}`]: () => Type[Property]
};
interface Person1 {
name: string;
age: number;
location: string;
}
type LazyPerson = Getters<Person1>;
type EventConfig<Events extends { kind: string }> = {
[E in Events as E["kind"]]: (event: E) => void;
}
type SquareEvent = { kind: "square", x: number, y: number };
type CircleEvent = { kind: "circle", radius: number };
type Config = EventConfig<SquareEvent | CircleEvent>
Literal Types
type Greeting = "Hello, world"
type ShoutyGreeting = Uppercase<Greeting>
type Greeting2 = "Hello, world"
type QuietGreeting = Lowercase<Greeting2>
type LowercaseGreeting = "hello, world";
type Greeting3 = Capitalize<LowercaseGreeting>;
type UppercaseGreeting = "HELLO WORLD";
type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;