常用类型
string
number
boolean
array
any
- noImplicitAny
function
- 参数类型注释typescript
function greet(name: string) { console.log("Hello, " + name.toUpperCase() + "!!"); }
- 返回类型注释typescript
function getFavoriteNumber(): number { return 26; }
typescriptasync function getFavoriteNumber(): Promise<number> { return 26; }
- 匿名函数typescript
const names = ["Alice", "Bob", "Eve"]; // Contextual typing for function - parameter s inferred to have type string names.forEach(function (s) { console.log(s.toUpperCase()); });
- 参数类型注释
object
- 定义对象类型typescript
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); }
- 可选属性typescript
function printName(obj: { first: string; last?: string }) { // ... }
- 定义对象类型
- 联合类型
- 定义联合类型typescript
function printId(id: number | string) { console.log("Your ID is: " + id); }
- 使用联合类型typescript
function printId(id: number | string) { if (typeof id === "string") { // In this branch, id is of type 'string' console.log(id.toUpperCase()); } else { // Here, id is of type 'number' console.log(id); } }
- 定义联合类型
type
类型别名typescripttype Point = { x: number; y:number; }
typescripttype ID = number | string;
interface
typescriptinterface Point { x: number; y: number; }
- 类型断言typescript
const myCanvas = document.getElementById("main_canvas") as HTMLCanvasElement;
typescriptconst a = expr as any as T;
- 文字类型typescript
type POSITION = 'left'|'right'; declare function handleRequest(url: string, method: "GET" | "POST"): void;
null
和undefined
- strictNullChecks
- 非空断言typescript
function liveDangerously(x?: number | null) { // No error console.log(x!.toFixed()); }
enum
枚举
不常用类型
bigint
symbol