Skip to content

Typescript 基础

知识地图

JS 和 TS

配置开发环境

JavaScript With Syntax For Types.

JavaScript With Syntax For Types.

TypeScript 中文网 · TypeScript——JavaScript 的超集

Terminal window
npm install -g typescript

Terminal window
tsc -v

const hello = "hello world";
console.log(hello);
Terminal window
tsc main.ts

Terminal window
tsc main.ts && node main.js

"code-runner.executorMap": {
"javascript": "node",
"typescript": "tsc -t es5 $fileName && node $fileNameWithoutExt.js",
},

TS 工作流

Terminal window
npm init -y
Terminal window
npm i lite-server --save-dev
"start": "lite-server"
Terminal window
npm run start

TS 类型

数字 number

const a = 123;
const b = 456;
function add(num1, num2) {
return num1 + num2;
}
console.log(add(a, b));
// ...
function add(num1: number, num2: number) {
// ...
}
// ...

布尔值 boolean

let isLogin: boolean;

字符串 string

var aaa = "zhangsan";
var bbb = "lisi";
var ccc = `wangwu`;
var aaa: string;
var bbb: string;
var ccc: string;
aaa = "zhangsan";
bbb = "lisi";
ccc = `wangwu`;

数组 array

// 定义一个list1, 类型是number数组
let list1: number[] = [1, 2, 3, 4, 5];
// 定义一个list2, 类型是number数组
let list2: Array<number> = [6, 7, 8, 9, 0];
// 定义一个list3, 类型是number数组
let list3 = [1, 2, 3, 4, 5];

let list4 = [1, "a"];
let list5: any[] = [1, "a"];
let list6: Array<any> = [1, "a"];
list4.push("aaa");
list5.push(123);
list6.push("abcd");

元组 tuple

// 数组有两个元素, 并且第一个元素必须是数字, 第二个元素必须是字符串
let person: [number, string] = [11111, "zhangsan"];
person[0] = 456;
person[1] = 456;
person[0] = "zhangsan";
person[1] = "lisi";

let person: [number, string] = [11111, "zhangsan"];
console.log(person[2]);

let person: [number, string] = [11111, "zhangsan"];
person.push("123");
console.log(person);

let person: [number, string] = [11111, "zhangsan"];
let person2 = [11111, "zhangsan"];

let person2 = [11111, "zhangsan"];
person2[0] = "lisi";
person2[1] = 123;
person2[2] = "hello";
console.log(person2);

联合类型 union

let a: string | number;
let a: string | number;
a = "hello";
a = 123;
a = [1, 2, 3];

let b: number | string | boolean | string[];
let b: number | string | boolean | string[];
b = 10;
b = "hello";
b = true;
b = ["hello", "world"];
b = [1, 2, 3];

function merge(a, b) {
return a + b;
}
const mergeNumber = merge(1, 2);
console.log(mergeNumber);
function merge(a: number, b: number) {
return a + b;
}
const mergeNumber = merge("hello", "world");
console.log(mergeNumber);

function merge(a: number | string, b: number | string) {
return a + b;
}
const mergeNumber = merge(1, 2);
const mergeString = merge("hello", "world");
console.log(mergeNumber);

function merge(a: number | string, b: number | string) {
if (typeof a === "string" || typeof b === "string") {
return a.toString() + b.toString();
} else {
return a + b;
}
}
const mergeNumber = merge(1, 2);
const mergeString = merge("hello", "world");
console.log(mergeNumber);
console.log(mergeString);

字面量类型 literal

const a = 123;
let b = 456;

let a: 0 | 1 | 2;
a = 1;
a = 2;
a = 3;

let a: 1 | "2" | true | [1, 2, 3];
function merge(a: number | string, b: number | string, resultType: "as-number" | "as-string") {
if (resultType === "as-string") {
return a.toString() + b.toString();
}
if (resultType === "as-number") {
return +a + +b;
}
}
const merge1 = merge(1, 2, "as-string");
const merge2 = merge("123", "456", "as-number");
console.log(merge1);
console.log(merge2);

枚举类型 Enum

// 定义颜色的枚举类型
enum Color {
red,
green,
blue,
}
// 使用
console.log(Color.red); // 0
console.log(Color.green); // 1
console.log(Color.blue); // 2

// 定义颜色的枚举类型
enum Color {
red = 1,
green = 3,
blue = 5,
}
// 使用
console.log(Color.red); // 1
console.log(Color.green); // 3
console.log(Color.blue); // 5
// 定义颜色的枚举类型
enum Color {
red = "红色!!!",
green = "绿色!!!",
blue = "蓝色!!!",
}
// 使用
console.log(Color.red); // 红色!!!
console.log(Color.green); // 绿色!!!
console.log(Color.blue); // 蓝色!!!

任意类型 any

let a: any;
a = 123;
a = "hello";
a = true;
a = [1, 2, 3];
a = { name: "zhangsan" };

未知类型 unkown

let a: unknown;
a = 123;
if (typeof a === "function") {
a();
}
if (typeof a === "string") {
a.toUpperCase();
}

空白类型 void

function demo(): type {}

未定义 undefined

2023 年 8 月 18 日 22:17:50 版本: 5.1.6 现在这个问题已经解决了, 不写默认就相当于是return undefined

永不类型 never

类型断言/类型适配 Type Assertions

let a: any = "hello";
console.log(a.endsWith("s"));

"typescript": "tsc -t es6 $fileName && node $fileNameWithoutExt.js",

let a: any = "hello";
console.log((a as string).endsWith("o"));
let a: any = "hello";
console.log((<string>a).endsWith("o"));

函数类型 function

let a = function (message) {
console.log(message);
};
let b = (message) => console.log(message);

let b = (message: string, code: number) => console.log(message, code);
b("Hello", 123);

对象类型 object

接口 interface

function demo(position) {
// 解构赋值
const { x, y } = position;
// 打印
console.log(`x轴位置: ${x}, y轴位置: ${y}`); // x轴位置: 111, y轴位置: 222
}
demo({ x: 111, y: 222 });

// 定义一个接口
interface Pos {
x: number;
y: number;
}
function demo(position: Pos) {
const { x, y } = position;
console.log(`x轴位置: ${x}, y轴位置: ${y}`);
}
demo({ x: 111, y: 222 });
demo({ x: "hello", y: "world" });
demo({ a: 1, b: 2 });

高内聚, 低耦合

类好比是“蓝图”

实例是具体的对象

类和实例

类 class

interface IPoint {
x: number;
y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}

class Point implements IPoint {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
drawPoint = () => {
console.log(this.x, this.y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
/**
* 表示一个点的接口。
*/
interface IPoint {
/**
* X 坐标值。
*/
x: number;
/**
* Y 坐标值。
*/
y: number;
/**
* 绘制该点的方法。
*/
drawPoint: () => void;
/**
* 获取该点与另一个点之间的距离。
* @param point 另一个点的坐标。
* @returns 两点之间的距离。
*/
getDistance: (point: { x: number; y: number }) => number;
}
/**
* 表示一个具体的点对象,实现了 IPoint 接口。
*/
class Point implements IPoint {
/**
* X 坐标值。
*/
x: number;
/**
* Y 坐标值。
*/
y: number;
/**
* 创建一个新的点对象。
* @param x X 坐标值。
* @param y Y 坐标值。
*/
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
/**
* 绘制该点的方法。
*/
drawPoint = () => {
console.log(this.x, this.y);
};
/**
* 获取该点与另一个点之间的距离。
* @param point 另一个点的坐标。
* @returns 两点之间的距离。
*/
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
// 实例化一个点对象
// 这段代码创建了一个名为point的Point对象,其初始坐标为(24, 50)。然后,通过调用point对象的getDistance方法,并传入参数{ x: 11, y: 12 },计算了该点与给定参数点之间的距离。最后,将计算得到的距离打印在控制台上。
const point = new Point(24, 50);
console.log(point.getDistance({ x: 11, y: 12 }));

/**
* 表示一个点的接口。
*/
interface IPoint {
/**
* X 坐标值。
*/
x: number;
/**
* Y 坐标值。
*/
y: number;
/**
* 绘制该点的方法。
*/
drawPoint: () => void;
/**
* 获取该点与另一个点之间的距离。
* @param point 另一个点的坐标。
* @returns 两点之间的距离。
*/
getDistance: (point: { x: number; y: number }) => number;
}
/**
* 表示一个具体的点对象,实现了 IPoint 接口。
*/
class Point implements IPoint {
/**
* X 坐标值。
*/
x: number;
/**
* Y 坐标值。
*/
y: number;
/**
* 创建一个新的点对象。
* @param x X 坐标值。
* @param y Y 坐标值。
*/
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
/**
* 绘制该点的方法。
*/
drawPoint = () => {
console.log(this.x, this.y);
};
/**
* 获取该点与另一个点之间的距离。
* @param point 另一个点的坐标。
* @returns 两点之间的距离。
*/
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
// 实例化一个点对象
// 这段代码创建了一个名为point的Point对象,其初始坐标为(24, 50)。然后,通过调用point对象的getDistance方法,并传入参数{ x: 11, y: 12 },计算了该点与给定参数点之间的距离。最后,将计算得到的距离打印在控制台上。
const point = new Point(24, 50);
console.log(point.getDistance({ x: 11, y: 12 }));

访问修饰符 Access Modifier

调用位置public(公共的)protected(受保护的)private(私有的)
类外部(实例化对象)✔️
类内部(子类)✔️✔️
类内部(自身)✔️✔️✔️
// 定义接口
interface IPoint {
x: number;
y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(public x: number, public y: number) {}
drawPoint = () => {
console.log(this.x, this.y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
const point = new Point(24, 50);
console.log(point.x, point.y);

// 定义接口
interface IPoint {
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(protected x: number, protected y: number) {}
drawPoint = () => {
console.log(this.x, this.y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
const point = new Point(24, 50);
console.log(point.x, point.y);

// 定义接口
interface IPoint {
// x: number;
// y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private x: number, private y: number) {}
drawPoint = () => {
console.log(this.x, this.y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
const point = new Point(24, 50);
console.log(point.x, point.y);

// 定义接口
interface IPoint {
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private x: number, private y: number) {}
drawPoint = () => {
console.log(this.x, this.y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this.x);
const b = Math.abs(point.y - this.y);
return Math.sqrt(a * a + b * b);
};
}
const point = new Point(24, 50);
point.drawPoint();

// 定义接口
interface IPoint {
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private _x: number, private _y: number) {}
drawPoint = () => {
console.log(this._x, this._y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this._x);
const b = Math.abs(point.y - this._y);
return Math.sqrt(a * a + b * b);
};
}
const point = new Point(24, 50);
point.drawPoint();

getter 和 setter

// 定义接口
interface IPoint {
getX: () => number;
setX: (value: number) => void;
getY: () => number;
setY: (value: number) => void;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private _x: number, private _y: number) {}
drawPoint = () => {
console.log(this._x, this._y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this._x);
const b = Math.abs(point.y - this._y);
return Math.sqrt(a * a + b * b);
};
getX = () => {
return this._x;
};
setX = (value: number) => {
this._x = value;
};
getY = () => {
return this._y;
};
setY = (value: number) => {
this._y = value;
};
}
const point = new Point(24, 50);
point.setX(111);
console.log(point.getX());
point.setY(222);
console.log(point.getY());
// 定义接口
interface IPoint {
X: number;
Y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private _x: number, private _y: number) {}
drawPoint = () => {
console.log(this._x, this._y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this._x);
const b = Math.abs(point.y - this._y);
return Math.sqrt(a * a + b * b);
};
get X() {
return this._x;
}
set X(value: number) {
this._x = value;
}
get Y() {
return this._y;
}
set Y(value: number) {
this._y = value;
}
}
const point = new Point(24, 50);
point.X = 111;
console.log(point.X);
point.Y = 222;
console.log(point.Y);

"typescript": "tsc -t es5 $fileName && node $fileNameWithoutExt.js",

module 模块

// 定义接口
interface IPoint {
X: number;
Y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
class Point implements IPoint {
constructor(private _x: number, private _y: number) {}
drawPoint = () => {
console.log(this._x, this._y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this._x);
const b = Math.abs(point.y - this._y);
return Math.sqrt(a * a + b * b);
};
get X() {
return this._x;
}
set X(value: number) {
this._x = value;
}
get Y() {
return this._y;
}
set Y(value: number) {
this._y = value;
}
}
const point = new Point(24, 50);
point.X = 111;
console.log(point.X);
point.Y = 222;
console.log(point.Y);
// 定义接口
interface IPoint {
X: number;
Y: number;
drawPoint: () => void;
getDistance: (point: { x: number; y: number }) => number;
}
// 定义类, 实现接口
class Point implements IPoint {
constructor(private _x: number, private _y: number) {}
drawPoint = () => {
console.log(this._x, this._y);
};
getDistance = (point: { x: number; y: number }) => {
const a = Math.abs(point.x - this._x);
const b = Math.abs(point.y - this._y);
return Math.sqrt(a * a + b * b);
};
get X() {
return this._x;
}
set X(value: number) {
this._x = value;
}
get Y() {
return this._y;
}
set Y(value: number) {
this._y = value;
}
}

"typescript": "tsc -t es5 $fileName && node $fileNameWithoutExt.js",

import Point from "./Point";
const point = new Point(24, 50);
point.X = 111;
point.Y = 222;
console.log(point.X, point.Y);

泛型 Generics

let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3];
function firstElement(arr: any[]) {
return arr[0];
}
const arr = [1, 2, 3, 4, 5];
console.log(firstElement(arr)); // 1

function firstElement(arr: (number | string)[]) {
return arr[0];
}
const arr = [1, 2, 3, 4, 5];
console.log(firstElement(arr));

function firstElement<Type>(arr: Type[]): Type {
return arr[0];
}
const arr = [1, 2, 3, 4, 5];
console.log(firstElement(arr));

function firstElement<Type>(arr: Type[]): Type {
return arr[0];
}
const arr = ["a", "b", "c"];
console.log(firstElement(arr));

function firstElement<Type>(arr: Type[]): Type {
return arr[0];
}
const arr = ["a", "b", "c"];
console.log(firstElement<string>(arr));

类型守护 Type Guards

// 正方形类型
type Square = {
size: number;
};
// 定义一个长方形类型
type Rectangle = {
width: number;
height: number;
};
// 定义一个形状类型
type Shape = Square | Rectangle;
// 定义一个函数, 求面积, 传入的参数是一个形状类型
function area(shape: Shape) {
// 如果参数中有size, 就说明是正方形, 返回size的平方
if ("size" in shape) {
return shape.size * shape.size;
}
// 如果参数中有width, 说明是长方形, 返回长乘宽
if ("width" in shape) {
return shape.width * shape.height;
}
}
// 调用函数
console.log(area({ size: 12 }));
// 正方形类型
type Square = {
size: number;
};
// 定义一个长方形类型
type Rectangle = {
width: number;
height: number;
};
// 定义一个形状类型
type Shape = Square | Rectangle;
// 定义函数判断是否是正方形, 返回boolean
function isSquare(shape: Shape): shape is Square {
return "size" in shape;
}
// 定义函数判断是否是长方形, 返回boolean
function isRectangle(shape: Shape): shape is Rectangle {
return "width" in shape;
}
// 定义函数, 计算面积, 传入形状
function area(shape: Shape) {
// 如果是正方形
if (isSquare(shape)) {
// 计算平方
return shape.size * shape.size;
}
// 如果是长方形
if (isRectangle(shape)) {
// 计算宽乘以高
return shape.width * shape.height;
}
}
// 调用函数
console.log(area({ size: 12 }));

函数重载 Function Overloading

function myReverse(stringOrArray: string | string[]) {
// 判断参数的数据类型
if (typeof stringOrArray === "string") {
return stringOrArray.split("").reverse().join("");
} else {
return stringOrArray.reverse();
}
}
const arr = "abcdefg";
const arr1 = myReverse(arr);
console.log(arr1);

function myReverse(string: string): string;
function myReverse(array: string[]): string[];
function myReverse(stringOrArray: string | string[]) {
// 判断参数的数据类型
if (typeof stringOrArray === "string") {
return stringOrArray.split("").reverse().join("");
} else {
return stringOrArray.reverse();
}
}
const arr = ["a", "b", "c"];
const arr1 = myReverse(arr);
console.log(arr1);

function makeDate(timestampOrYear: number, month?: number, day?: number) {
if (month != null && day != null) {
// 如果传的格式是 年, 月, 日, 三个参数的情况
return new Date(timestampOrYear, month - 1, day);
} else {
// 如果是一个参数, 时间戳
return new Date(timestampOrYear);
}
}
const day1 = makeDate(2022, 1, 1); // 三个参数
const day2 = makeDate(1640966400000); // 一个参数
console.log(day1);
console.log(day2);
const day3 = makeDate(2022, 1); // 1970-01-01T00:00:02.022Z
function makeDate(timestamp: number): Date;
function makeDate(year: number, month: number, day: number): Date;
function makeDate(timestampOrYear: number, month?: number, day?: number) {
if (month != null && day != null) {
return new Date(timestampOrYear, month - 1, day);
} else {
return new Date(timestampOrYear);
}
}
const day1 = makeDate(2022, 1, 1);
const day2 = makeDate(1640966400000);
const day3 = makeDate(2022, 1);
console.log(day1); // 2021-12-31T16:00:00.000Z
console.log(day2); // 2021-12-31T16:00:00.000Z

函数调用签名 Call Signatures

function add(num1: number, num2: number): number {
return num1 + num2;
}
function minus(num1: number, num2: number): number {
return num1 - num2;
}
function multi(num1: number, num2: number): number {
return num1 * num2;
}
function division(num1: number, num2: number): number {
return num1 / num2;
}
type count = {
(num1: number, num2: number): number;
};
const add: count = (num1, num2) => {
return num1 + num2;
};
const minus: count = (num1, num2) => {
return num1 - num2;
};
const multi: count = (num1, num2) => {
return num1 * num2;
};
const division: count = (num1, num2) => {
return num1 / num2;
};
type count = {
(num1: number, num2: number): number;
(num1: number, num2: number, num3: number): number;
};
const add: count = (num1, num2, num3?) => {
if (num3) {
return num1 + num2 + num3;
} else {
return num1 + num2;
}
};
type count = (num1: number, num2: number, num3?: number) => number;
const add: count = (num1, num2, num3?) => {
if (num3 !== undefined) {
return num1 + num2 + num3;
}
return num1 + num2;
};
const minus: count = function (num1, num2) {
return num1 - num2;
};
const multi: count = function (num1, num2) {
return num1 * num2;
};
const division: count = function (num1, num2) {
return num1 / num2;
};

索引签名 Index Signatures

const user = {
username: "zhangsan",
};
console.log(user["username"]); // zhangsan
const student = {
1111: "xiaoming",
};
console.log(student[1111]); // xiaoming
type Person = {
name: string;
email: string;
};
type PersonDictionary = {
[key: string]: Person;
};
const obj: PersonDictionary = {
zhangsan: {
name: "张三",
email: "zhangsan@163.com",
},
lisi: {
name: "李四",
email: "lisi@126.com",
},
};

type Person = {
name: string;
email: string;
};
type PersonDictionary = {
[key: string]: Person;
};
const obj: PersonDictionary = {
zhangsan: {
name: "张三",
email: "zhangsan@163.com",
},
lisi: {
name: "李四",
email: "lisi@126.com",
},
};
// 读取值
const zhangsan = obj["zhangsan"];
console.log(zhangsan);
// 赋值
obj["wangwu"] = {
name: "王五",
email: "wangwu@163.com",
};
// 删除
delete obj["zhangsan"];
console.log(obj);

只读 readonly

function reverseSorted(input: number[]): number[] {
return input.sort().reverse();
}
const a = [1, 2, 3, 4, 5];
const result = reverseSorted(a);
console.log(a);
console.log(result);

function reverseSorted(input: readonly number[]): number[] {
return [...input].sort().reverse();
}
const a = [1, 2, 3, 4, 5];
const result = reverseSorted(a);
console.log(a); // [ 1, 2, 3, 4, 5 ]
console.log(result); // [ 5, 4, 3, 2, 1 ]

双重断言 Double Assertion

type Point2D = { x: number; y: number };
type Point3D = { x: number; y: number; z: number };
type Person = { name: string; email: string };
let point2: Point2D = { x: 0, y: 0 };
let point3: Point3D = { x: 10, y: 10, z: 10 };
let person: Person = { name: "zhangsan", email: "zhangsan@126.com" };
point2 = point3; // 成功
point3 = point2; // 失败

point2 = point3; // 成功
point3 = point2 as Point3D; // 类型断言, 不报错了

person = point3; //error
point3 = person; //error

person = point3 as Person; //error
point3 = person as Point3D; //error

person = point3 as any as Person; //不报错了
point3 = person as any as Point3D; //不报错了

常量断言 const Assertion

const user = {
username: "zhangsan",
age: 18,
};
user.username = "lisi";
user.age = 19;
console.log(user);
const user = {
username: "zhangsan",
age: 18,
} as const;

const user = {
username: "zhangsan",
age: 18,
hobby: ["抽烟", "喝酒", "烫头"],
} as const;

function layout(setting: { align: "left" | "center" | "right"; padding: number }) {
console.log("Layout: ", setting);
}
const paramater = {
align: "left",
padding: 0,
};
layout(paramater);

const paramater = {
align: "left" as const,
padding: 0,
};

ts 中的 this

function double() {
this.age = this.age * 2;
}
const user = {
age: 10,
double,
};
user.double();
console.log(user.age);
function double() {
this.ag = this.ag * 2;
}
function double() {
this.ag = this.ag * 2;
}
const user = {
age: 10,
double,
};
user.double();
console.log(user.age); // 10
function double(this: { age: number }) {
this.ag = this.ag * 2;
}

function double(this: { age: number }) {
this.age = this.age * 2;
}
const user = {
age: 10,
double,
};
user.double();
console.log(user.age); // 20

typeof 操作符

// 中心点
const center = {
x: 0,
y: 0,
};
// 定义一个单位
const unit1 = {
x: center.x * 10,
y: center.y * 10,
};
// 定义一个单位
const unit2 = {
x: center.x * 100,
y: center.y * 100,
};
// 定义一个单位
const unit3 = {
x: center.x * 1000,
y: center.y * 1000,
};
const center = {
x: 0,
y: 0,
z: 0,
};
// ...
type point = {
x: number;
y: number;
z: number;
};
// ...
//...
// 定义一个单位
const unit1: point = {
x: center.x * 10,
y: center.y * 10,
};
// 定义一个单位
const unit2: point = {
x: center.x * 100,
y: center.y * 100,
};
// 定义一个单位
const unit3: point = {
x: center.x * 1000,
y: center.y * 1000,
};

type point = typeof center;
// 中心点
const center = {
x: 0,
y: 0,
z: 0,
};
// ...

// 中心点
const center = {
x: 0,
y: 0,
z: 0,
};
// 定义一个单位
const unit1: typeof center = {
x: center.x * 10,
y: center.y * 10,
};
// 定义一个单位
const unit2: typeof center = {
x: center.x * 100,
y: center.y * 100,
};
// 定义一个单位
const unit3: typeof center = {
x: center.x * 1000,
y: center.y * 1000,
};

keyof 操作符

type Person = {
username: string;
age: number;
location: string;
};
const user: Person = {
username: "zhangsan",
age: 18,
location: "深圳",
};
function getValueByKey(obj, key) {
const value = obj[key];
return value;
}
console.log(getValueByKey(user, "username")); // zhangsan

function getValueByKey(obj: Person, key: "username" | "age" | "location") {
const value = obj[key];
return value;
}

function getValueByKey(obj: Person, key: keyof Person) {
const value = obj[key];
return value;
}

function getValueByKey<Obj, Key extends keyof Obj>(obj: Obj, key: Key) {
const value = obj[key];
return value;
}

类型查找 lookup types

// 服务器的数据的结构, 转账交易记录
type RequestData = {
// 交易id
transactionId: string;
// 用户信息
user: {
name: string;
email: string;
phone: string;
nickname: string;
gender: string;
dob: string;
nationality: string;
address: {
stress: string;
unitNumber: string;
city: string;
provance: string;
contury: string;
}[];
};
// 驾照信息
dirverInfo: {
licenceNumber: string;
exporyDate: string;
classes: string;
status: string;
};
// 交易信息
payment: {
creditCardNumber: string;
};
};
function getPayment() {
return {
creditCardNumber: "1234567890",
};
}
function getPayment(): { creditCardNumber: string } {
return {
creditCardNumber: "1234567890",
};
}

type PaymentRequestType = {
creditCardNumber: string;
};
function getPayment(): PaymentRequestType {
return {
creditCardNumber: "1234567890",
};
}
// 提交给服务器的数据结构
type RequestData = {
// ...
payment: PaymentRequestType;
};

// 提交给服务器的数据结构
type RequestData = {
// ...
payment: {
creditCardNumber: string;
};
};
function getPayment() {
return {
creditCardNumber: "1234567890",
};
}
function getPayment(): RequestData["payment"] {
return {
creditCardNumber: "1234567890",
};
}

// 交易信息
payment: {
creditCardNumber: string;
alipay: string;
}

类型映射 Mapped Types

type Point = {
x: number;
y: number;
z: number;
};
const center: Point = {
x: 0,
y: 0,
z: 0,
};
// ...
center.x = 1;
center.y = 1;
center.z = 1;
console.log(center);

// ...
type ReadOnlyPoint = {
readonly x: number;
readonly y: number;
readonly z: number;
};
const center: ReadOnlyPoint = {
x: 0,
y: 0,
z: 0,
};
// ...

type Point = {
x: number;
y: number;
z: number;
};
type ReadOnlyPoint = {
readonly [key in "x" | "y" | "z"]: number;
};
// ...
type ReadOnlyPoint = {
readonly [key in keyof Point]: number;
};
type ReadOnlyPoint = {
readonly [key in keyof Point]: Point[key];
};
type Point = {
x: number;
y: number;
z: number;
};
type isReadonlyType<T> = {
readonly [key in keyof T]: T[key];
};
const center: isReadonlyType<Point> = {
x: 0,
y: 0,
z: 0,
};
// ...
type Point = {
x: number;
y: number;
z: number;
};
const center: Readonly<Point> = {
x: 0,
y: 0,
z: 0,
};
center.x = 1;
center.y = 1;
center.z = 1;
console.log(center);