2023/10/04
posted in
TypeScript
#typescript
2023/10/04
posted in
TypeScript
#typescript
简单来讲,类型别名就是给一个类型起一个新名字。
简单的例子:
type Name = string
type NameResolver = () => string
type NameOrResolver = Name | NameResolver
function getName(n: NameOrResolver): Name {
if (typeof n === 'string') {
return n;
} else {
return n();
}
}
上例中,我们使用 type
创建类型别名。
类型别名常用于联合类型。
类型别名与接口非常相似,他们两者可以相互选择
interface Person {
name: string;
age: number
}
type Person = {
name: string;
age: number
}
interface Person {
name: string;
}
interface Person {
age: number
}
const person: Person = {
name: 'xiaohong',
age: 18
}
Type | interface |
---|---|
只能通过&进行合并 | 同名自动合并,通过extends扩展 |
更强大,除了以上类型还支持 string 数组... | 自身只能表达 object/class/function类型 |
建议:能用 interface 实现,就用 interface , 如果不能才用 type
字符串字面量类型用来约束取值只能是某几个字符串的一个。
例子:
tyep EventNames = 'click' | 'scroll' | 'mouseove'
function handleEvent(ele: Element, event: EventNames) {
// todo
}
andleEvent(document.getElementById('hello'), 'scroll'); // 没问题
handleEvent(document.getElementById('world'), 'dblclick'); // 报错,event 不能为 'dblclick'
上例中,我们使用 type
定了一个字符串字面量类型 EventNames
,它只能取三种字符串中的一种。
除了字符串字面量类型之外,TypeScript 同样也提供 boolean
和 number
的字面量类型:
type OneToFive = 1 | 2 | 3 | 4 | 5;
type Bools = true | false;
注意,类型别名与字符串字面量类型都是使用 type
进行定义。
数组合并了相同类型的对象,而元组(Tuple)合并了不同类型的对象。
元组类型允许表示一个已知元素数量和类型的数组,各元素的类型不必相同。
元组起源于函数编程语言(如 F#),这些语言中会频繁使用元组。
简单的例子:
定义一对值分别为string
和number
的元组
let tom: [string, number] = ['Tom', 25]
当赋值或访问一个已知索引的元素时,会得到正确的类型:
let tom:[string, number]
tom[0] = 'Tom'
tom[1] = 25
tom[0].slice(1)
tom[1].fixed(2)
也可以赋值其中一项:
let tom = [string, number]
tom[0] = 'tom'
但是当直接对元组类型的变量进行初始化或者赋值的时候,需要提供所有元素类型中指定的项。
let tom: [string, number]
tom = ['Tom', 25]
let tom: [string, number]
tom = ['25']
// Property '1' is missing in type '[string]' but required in type '[string, number]'
当添加越界的元素时,它的类型会被限制为元组中每个类型的联合类型:
let tom: [string, number];
tom = ['Tom', 25];
tom.push('male');
tom.push(true);
// Argument of type 'true' is not assignable to parameter of type 'string | number'.
枚举(Enum)类型用于取值被限定在一定范围内的场景,比如一周只能有七天,颜色限定为红绿蓝等。
枚举使用 enum
关键字来定义:
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat}
枚举成员会被赋值为从 0
开始递增的数字,同时也会对枚举值到枚举名进行反向映射:
enum Days {Sun, Mon, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 0); // true
console.log(Days["Mon"] === 1); // true
console.log(Days["Tue"] === 2); // true
console.log(Days["Sat"] === 6); // true
console.log(Days[0] === "Sun"); // true
console.log(Days[1] === "Mon"); // true
console.log(Days[2] === "Tue"); // true
console.log(Days[6] === "Sat"); // true
我们也可以给枚举项手动赋值:
enum Days {Sun = 3, Mon = 1, Tue, Wed, Thu, Fri, Sat}
console.log(Days["Sun"] === 3); // true
console.log(Days["Wed"] === 3); // true
console.log(Days[3] === "Sun"); // false
console.log(Days[3] === "Wed"); // true
上面的例子中,未手动赋值的枚举项会接着上一个枚举项递增。
如果未手动赋值的枚举项与手动赋值的重复了,TypeScript 是不会察觉到这一点的:
enum Days {Sun = 3, Mon = 1, Tue, Wed, Thu, Fri, Sat};
console.log(Days["Sun"] === 3); // true
console.log(Days["Wed"] === 3); // true
console.log(Days[3] === "Sun"); // false
console.log(Days[3] === "Wed"); // true
所以使用的时候需要注意,最好不要出现这种覆盖的情况。
手动赋值的枚举项可以不是数字,此时需要使用类型断言来让 tsc 无视类型检查 (编译出的 js 仍然是可用的):
enum Days {Sun = 7, Mon, Tue, Wed, Thu, Fri, Sat = <any>"S"};
类型的断言 值 as 类型 | 或者<类型>值
当然,手动赋值的枚举项也可以为小数或负数,此时后续未手动赋值的项的递增步长仍为 1
:
枚举项有两种类型:常数项(constant member)和计算所得项(computed member)。
前面我们所举的例子都是常数项,一个典型的计算所得项的例子:
enum Color {Red, Green, Blue = 'blue'.length}
上面的例子中,"blue".length
就是一个计算所得项。
上面的例子不会报错,但是如果紧接在计算所得项后面的是未手动赋值的项,那么它就会因为无法获得初始值而报错:
enum Color {Red = "red".length, Green, Blue};
// error TS1061: Enum member must have initializer.
// error TS1061: Enum member must have initializer.
下面是常数项和计算所得项的完整定义,部分引用自中文手册 - 枚举:
当满足以下条件时,枚举成员被当作是常数:
1
。但第一个枚举元素是个例外。如果它没有初始化方法,那么它的初始值为 0
。+
, -
, ~
一元运算符应用于常数枚举表达式+
, -
, *
, /
, %
, <<
, >>
, >>>
, &
, |
, ^
二元运算符,常数枚举表达式做为其一个操作对象。若常数枚举表达式求值后为 NaN 或 Infinity,则会在编译阶段报错所有其它情况的枚举成员被当作是需要计算得出的值。
常数枚举是使用 const enum
定义的枚举类型:
const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
上例的编译结果是:
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
假如包含了计算成员,则会在编译阶段报错:
const enum Color {Red, Green, Blue = "blue".length};
// error TS2474: In 'const' enum declarations member initializer must be constant expression.
外部枚举(Ambient Enums)是使用 declare enum
定义的枚举类型:
declare enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
之前提到过,declare
定义的类型只会用于编译时的检查,编译结果中会被删除。
上例的编译结果是:
var directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
外部枚举与声明语句一样,常出现在声明文件中。
同时使用 declare
和 const
也是可以的:
declare const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
编译结果:
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
交叉类型是将多个类型合并为一个类型
interface A {
name: string;
age: number
}
interface B {
email: string
}
type C = A & B
interface A {
name: string;
age: number
}
interface B {
name: string;
email: string
}
type C = A & B
const c : C = {
name: 'XXX',
age: 18,
email: 'xxxxxx'
}
type A = string | number
type B = string | boolean
type C = A & B
联合类型让一个值可以为不同的类型,但随之带来的问题就是访问非共同方法时会报错。那么该如何区分值的具体类型,以及如何访问共有成员?
function doSome(x: number | string) {
if (typeof x === 'string') {
// 在这个块中,TypeScript 知道 `x` 的类型必须是 `string`
console.log(x.substr(1)); // ok
}
x.substr(1); // Error: 无法保证 `x` 是 `string` 类型
}
class Foo {
foo = 123;
common = '123';
}
class Bar {
bar = 123;
common = '123';
}
function doStuff(arg: Foo | Bar) {
if (arg instanceof Foo) {
console.log(arg.foo); // ok
console.log(arg.bar); // Error
}
if (arg instanceof Bar) {
console.log(arg.foo); // Error
console.log(arg.bar); // ok
}
}
doStuff(new Foo());
doStuff(new Bar());
in
操作符可以安全的检查一个对象上是否存在一个属性,它通常也被作为类型保护使用:
interface A {
x: number;
}
interface B {
y: string;
}
function doStuff(q: A | B) {
if ('x' in q) {
// q: A
} else {
// q: B
}
}
当你在联合类型里使用字面量类型时,你可以检查它们是否有区别:
type Foo = {
kind: 'foo'; // 字面量类型
foo: number;
};
type Bar = {
kind: 'bar'; // 字面量类型
bar: number;
};
function doStuff(arg: Foo | Bar) {
if (arg.kind === 'foo') {
console.log(arg.foo); // ok
console.log(arg.bar); // Error
} else {
// 一定是 Bar
console.log(arg.foo); // Error
console.log(arg.bar); // ok
}
}
函数中使用 is 定位类型,这仅仅是一个返回值为类似于someArgumentName is SomeType
的函数
// 仅仅是一个 interface
interface Foo {
foo: number;
common: string;
}
interface Bar {
bar: number;
common: string;
}
// 用户自己定义的类型保护!
function isFoo(arg: Foo | Bar): arg is Foo {
return (arg as Foo).foo !== undefined;
}
// 用户自己定义的类型保护使用用例:
function doStuff(arg: Foo | Bar) {
if (isFoo(arg)) {
console.log(arg.foo); // ok
console.log(arg.bar); // Error
} else {
console.log(arg.foo); // Error
console.log(arg.bar); // ok
}
}
doStuff({ foo: 123, common: '123' });
doStuff({ bar: 123, common: '123' });
传统方法中,JavaScript 通过构造函数实现类的概念,通过原型链实现继承。而在 ES6 中,我们终于迎来了 class
。
TypeScript 除了实现了所有 ES6 中的类的功能以外,还添加了一些新的用法。
这一节主要介绍类的用法,下一节再介绍如何定义类的类型。
虽然 JavaScript 中有类的概念,但是可能大多数 JavaScript 程序员并不是非常熟悉类,这里对类相关的概念做一个简单的介绍。
new
生成Cat
和 Dog
都继承自 Animal
,但是分别实现了自己的 eat
方法。此时针对某一个实例,我们无需了解它是 Cat
还是 Dog
,就可以直接调用 eat
方法,程序会自动判断出来应该如何执行 eat
public
表示公有属性或方法使用class
定义类,使用constructor
定义构造函数
通过new
生成新实例的时候,会自动调用构造函数
class Animal {
public name;
constructor(name) {
this.name = name
}
sayHi() {
return `My name is ${this.name}`;
}
}
let a = new Animal('Jack')
console.log(a.sayHi()); // My name is Jack
使用extends
关键字实现继承,子类中使用super关键字来调用父类的构造函数和方法
class Cat extends Animal {
constructor(name) {
super(name); // 调用父类的 constructor(name)
console.log(this.name);
}
sayHi() {
return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi()
}
}
let c = new Cat('Tom'); // Tom
console.log(c.sayHi()); // Meow, My name is Tom
使用getter和setter可以改变属性的赋值和读取行为;
class Animal {
constructor(name) {
this.name = name;
}
get name() {
return 'Jack';
}
set name(value) {
console.log('setter: ' + value);
}
}
let a = new Animal('Kitty'); // setter: Kitty
a.name = 'Tom'; // setter: Tom
console.log(a.name); // Jack
使用static
修饰符修饰的方法称为静态方法,他们不需要实例化,而是直接通过类来调用:
class Animal {
static isAnimal(a) {
return a instanceof Animal;
}
}
let a = new Animal('Jack');
Animal.isAnimal(a); // true
a.isAnimal(a); // TypeError: a.isAnimal is not a function
TypeScript 可以使用三种访问修饰符(Access Modifiers),分别是 public
、private
和 protected
。
public
修饰的属性或方法是公有的,可以在任何地方被访问到,默认所有的属性和方法都是 public
的private
修饰的属性或方法是私有的,不能在声明它的类的外部访问protected
修饰的属性或方法是受保护的,它和 private
类似,区别是它在子类中也是允许被访问的class Animal {
public name;
public constructor (name) {
this.name = name
}
}
let a = new Animal('Jack')
console.log(a.name) // Jack
a.name = 'Tom'
console.log(a.name) // Tom
面的例子中,name
被设置为了 public
,所以直接访问实例的 name
属性是允许的。
很多时候,我们希望有的属性是无法直接存取的,这时候就可以用 private
了:
class Animal {
private name;
public constructor (name) {
this.name = name
}
}
let a = new Animal('Jack')
console.log(a.name) // Jack
a.name = 'Tom' // a是私有的,不允许在外面赋值
// error TS2341: Property 'name' is private and only accessible within class 'Animal'.
使用 private
修饰的属性或方法,在子类中也是不允许访问的:
class Animal {
private name;
public constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
console.log(this.name);
}
}
// index.ts(11,17): error TS2341: Property 'name' is private and only accessible within class 'Animal'.
而如果是用 protected
修饰,则允许在子类中访问:
class Animal {
protected name;
public constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
console.log(this.name);
}
}
当构造函数修饰为 private
时,该类不允许被继承或者实例化:
class Animal {
public name;
private constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
}
let a = new Animal('Jack');
// index.ts(7,19): TS2675: Cannot extend a class 'Animal'. Class constructor is marked as private.
// index.ts(13,9): TS2673: Constructor of class 'Animal' is private and only accessible within the class declaration.
当构造函数修饰为 protected
时,该类只允许被继承:
class Animal {
public name;
protected constructor(name) {
this.name = name;
}
}
class Cat extends Animal {
constructor(name) {
super(name);
}
}
let a = new Animal('Jack');
// index.ts(13,9): TS2674: Constructor of class 'Animal' is protected and only accessible within the class declaration.
修饰符和readonly
还可以使用在构造函数参数中,等同于类中定义该属性同时给该属性赋值,使代码更简洁。
class Animal {
// public name: string;
public constructor(public name) {
// this.name = name;
}
}
只读属性关键字,只允许出现在属性声明或者索引签名或构造函数中。
class Animal {
readonly name;
public constructor(name) {
this.name = name;
}
}
let a = new Animal('Jack');
console.log(a.name); // Jack
a.name = 'Tom';
// index.ts(10,3): TS2540: Cannot assign to 'name' because it is a read-only property.
注意如果 readonly
和其他访问修饰符同时存在的话,需要写在其后面。
class Animal {
// public readonly name;
public constructor(public readonly name) {
// this.name = name;
}
}
abstract
用于定义抽象类和其中的抽象方法。
什么是抽象类?
首先,抽象类是不允许被实例化的:
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
let a = new Animal('Jack');
// index.ts(9,11): error TS2511: Cannot create an instance of the abstract class 'Animal'.
上面的例子中,我们定义了一个抽象类 Animal
,并且定义了一个抽象方法 sayHi
。在实例化抽象类的时候报错了。
其次,抽象类中的抽象方法必须被子类实现:
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
class Cat extends Animal {
public eat() {
console.log(`${this.name} is eating.`);
}
}
let cat = new Cat('Tom');
// index.ts(9,7): error TS2515: Non-abstract class 'Cat' does not implement inherited abstract member 'sayHi' from class 'Animal'.
上面的例子中,我们定义了一个类 Cat
继承了抽象类 Animal
,但是没有实现抽象方法 sayHi
,所以编译报错了。
下面是一个正确使用抽象类的例子:
abstract class Animal {
public name;
public constructor(name) {
this.name = name;
}
public abstract sayHi();
}
class Cat extends Animal {
public sayHi() {
console.log(`Meow, My name is ${this.name}`);
}
}
let cat = new Cat('Tom');
上面的例子中,我们实现了抽象方法 sayHi
,编译通过了。
需要注意的是,即使是抽象方法,TypeScript 的编译结果中,仍然会存在这个类,上面的代码的编译结果是:
var __extends =
(this && this.__extends) ||
function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() {
this.constructor = d;
}
d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new __());
};
var Animal = (function () {
function Animal(name) {
this.name = name;
}
return Animal;
})();
var Cat = (function (_super) {
__extends(Cat, _super);
function Cat() {
_super.apply(this, arguments);
}
Cat.prototype.sayHi = function () {
console.log('Meow, My name is ' + this.name);
};
return Cat;
})(Animal);
var cat = new Cat('Tom');
给类加上 TypeScript 的类型很简单,与接口类似
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
sayHi(): string {
return `My name is ${this.name}`;
}
}
let a: Animal = new Animal('Jack');
console.log(a.sayHi()); // My name is Jack
实现(implements)是面向对象中的一个重要概念。一般来讲,一个类只能继承自另一个类,有时候不同类之间可以有一些共有的特性,这时候就可以把特性提取成接口(interfaces),用 implements
关键字来实现。这个特性大大提高了面向对象的灵活性。
举例来说,门是一个类,防盗门是门的子类。如果防盗门有一个报警器的功能,我们可以简单的给防盗门添加一个报警方法。这时候如果有另一个类,车,也有报警器的功能,就可以考虑把报警器提取出来,作为一个接口,防盗门和车都去实现它:
interface Alarm {
alert(): void
}
class SecurityDoor extends Door implements Alarm {
alert() {
console.log('SecurityDoor alert');
}
}
class Car implements Alarm {
alert() {
console.log('Car alert');
}
}
一个类可以实现多个接口:
interface Alarm {
alert(): void;
}
interface Light {
lightOn(): void;
lightOff(): void;
}
class Car implements Alarm, Light {
alert() {
console.log('Car alert');
}
lightOn() {
console.log('Car light on');
}
lightOff() {
console.log('Car light off');
}
}
上例中,Car
实现了 Alarm
和 Light
接口,既能报警,也能开关车灯。
接口与接口直接可以是继承关系:
interface Alarm {
alert(): void
}
interface LightableAlarm extends Alarm {
lightOn(): void;
lightOff(): void;
}
这很好理解,LightableAlarm
继承了 Alarm
,除了拥有 alert
方法之外,还拥有两个新方法 lightOn
和 lightOff
。
常见的面向对象语言中,接口时不能继承类的,但是在TypeScript中却是可以的。
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
为什么 TypeScript 会支持接口继承类呢?
实际上,当我们在声明 class Point
时,除了会创建一个名为 Point
的类之外,同时也创建了一个名为 Point
的类型(实例的类型)。
所以我们既可以将 Point
当做一个类来用(使用 new Point
创建它的实例):
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
const p = new Point(1, 2);
也可以将 Point
当做一个类型来用(使用 : Point
表示参数的类型):
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
function printPoint(p: Point) {
console.log(p.x, p.y);
}
printPoint(new Point(1, 2));
这个例子实际上可以等价于:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface PointInstanceType {
x: number;
y: number;
}
function printPoint(p: PointInstanceType) {
console.log(p.x, p.y);
}
printPoint(new Point(1, 2));
上例中我们新声明的 PointInstanceType
类型,与声明 class Point
时创建的 Point
类型是等价的。
所以回到 Point3d
的例子中,我们就能很容易的理解为什么 TypeScript 会支持接口继承类了:
class Point {
x: number;
y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
interface PointInstanceType {
x: number;
y: number;
}
// 等价于 interface Point3d extends PointInstanceType
interface Point3d extends Point {
z: number;
}
let point3d: Point3d = {x: 1, y: 2, z: 3};
当我们声明 interface Point3d extends Point
时,Point3d
继承的实际上是类 Point
的实例的类型。
换句话说,可以理解为定义了一个接口 Point3d
继承另一个接口 PointInstanceType
。
所以「接口继承类」和「接口继承接口」没有什么本质的区别。
值得注意的是,PointInstanceType
相比于 Point
,缺少了 constructor
方法,这是因为声明 Point
类时创建的 Point
类型是不包含构造函数的。另外,除了构造函数是不包含的,静态属性或静态方法也是不包含的(实例的类型当然不应该包括构造函数、静态属性或静态方法)。
换句话说,声明 Point
类时创建的 Point
类型只包含其中的实例属性和实例方法:
class Point {
/** 静态属性,坐标系原点 */
static origin = new Point(0, 0);
/** 静态方法,计算与原点距离 */
static distanceToOrigin(p: Point) {
return Math.sqrt(p.x * p.x + p.y * p.y);
}
/** 实例属性,x 轴的值 */
x: number;
/** 实例属性,y 轴的值 */
y: number;
/** 构造函数 */
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
/** 实例方法,打印此点 */
printPoint() {
console.log(this.x, this.y);
}
}
interface PointInstanceType {
x: number;
y: number;
printPoint(): void;
}
let p1: Point;
let p2: PointInstanceType;
上例中最后的类型 Point
和类型 PointInstanceType
是等价的。
同样的,在接口继承类的时候,也只会继承它的实例属性和实例方法。
泛型(Generics)是指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
先来看一段代码:
function join(a: number | string, b: number | string) {
return `${a} ${b}`;
}
这是一段很水的代码,作为萌新也一下就能看出来,a和b能传数字也能传字符串,最后的返回值,就是利用字符串模板将两者拼起来,其中我们传值有这么4种可能
但最终的结果依然是拼接,这个时候来了这么个需求,我们必须2个变量的类型要统一,我擦类,这怎么搞,这个时候掏出泛型,改写下代码并这么使用就可以了
function join<T> (a: T, b: T) {
return `${a} ${b}`;
}
join<number>(1, 2);
join<string>('1', '2');
// join<number>(1, '2'); //这行报错,你都规定是number了,字符串2是什么鬼
// join<string>(1, '2'); //这行也报错,你都规定是string了,数字1是什么鬼
在方法执行的括号前加上尖括号,指定类型就可以了(可以省略尖括号,ts会类型推断,但不建议这么做),这样也约束了参数的类型,这就是最基本最基础的一个使用方式了
我们同样也可以约束数组每一项的类型,比如写一个最简单的函数,传入个数组,并返回这个数组
function getArr<T>(arr: T[]) {
return arr;
}
getArr<number>([1, 2, 3]) //指定了number,那我的数组必须每一项也是number,如果不是就报错
getArr<string>(['g', 'q', 'f']) //同理这里指定了string
获取对象对应key的value,那大家都知道使用obj[key]
就可以了,但有的对象我们并不知道有没有这个key,用泛型的话可以很好的解决这个问题
function getVal<T>(obj: T, k: keyof T){
return obj[k];
}
interface Person {
name: string;
age: number;
}
getVal<Person>({
name: 'gqf',
age: 29
}, 'age') // 这里的key值只能传name或者age,否则就会报错,这个就是泛型的力量
function manyTest<K, V>(a: K, b: V) {
return `${a} ${b}`
}
manyTest<number, string>(1, '2') //泛型指定了第一个参数是数字,第二个参数是字符串,所以对应的参数也要这么传
模拟请求相应的场景,初始代码
interface IResponseData{
code: number;
message?: string;
data: any;
}
async function getData(url: string){
let response = await fetch(url);
let data = await response.json();
return data;
}
上述代码很明显有个问题,我们会发现该接口的data项的具体格式不确定,不同的接口会返回的数据是不一样的,当我们想根据具体当前请求的接口返回具体data格式的时候,就比较麻烦了,因为getData并不清楚你调用的具体接口是什么,对应的数据又会是什么,这个时候我们可以对IResponseData使用泛型
interface IResponseData<T>{
code: number;
message?: string;
data: T;
}
// 用户接口
interface IResponseUserData{
id: number;
username: string;
email: string;
}
// 文章接口
interface IResponseArticleData{
id: number;
title: string;
author: IResponseUserData;
}
async function getData<U>(url: string){
let response = await fetch(url);
let data: Promise<IResponseData<U>> = await response.json(); // 注意这里返回的是个Promise,然后我们根据不同的接口,指定不同的data数据格式
return data;
}
(async function(){
let userData = await getData<IResponseUserData>('/user');
userData.data.username;
let articleData = await getData<IResponseArticleData>('/article');
articleData.data.author.email;
})()
class AddClass<T> {
parmas: T;
add: (x: T, y: T) => T;
}
let addNumber = new AddClass<number>();
addNumber.parmas = 0;
addNumber.add = function(x, y) { return x + y; };
function returnParamsArr<T, U>(a: T, b:U):[U, T] {
return [b, a];
}
class AddClass<T, U> {
parmas: U;
add: (x: T, y: U) => [U, T];
}
interface Add<T, U> {
parmas: U;
add: (x: T, y: U) => [U, T];
}
你可以通过 typeof
操作符在类型注解中使用变量。这允许你告诉编译器,一个变量的类型与其他类型相同,如下所示:
let foo = 123;
let bar: typeof foo; // 'bar' 类型与 'foo' 类型相同(在这里是: 'number')
bar = 456; // ok
bar = '789'; // Error: 'string' 不能分配给 'number' 类型
与捕获变量的类型相似,你仅仅是需要声明一个变量用来捕获到的类型:
class Foo {
foo: number; // 我们想要捕获的类型
}
declare let _foo: Foo;
// 与之前做法相同
let bar: typeof _foo.foo;
keyof
操作符能让你捕获一个类型的键。例如,你可以使用它来捕获变量的键名称,在通过使用 typeof
来获取类型之后:
keyof
与 Object.keys
略有相似,只不过 keyof
取 interface
的键。
const colors = {
red: 'red',
blue: 'blue'
};
type Colors = keyof typeof colors;
let color: Colors; // color 的类型是 'red' | 'blue'
color = 'red'; // ok
color = 'blue'; // ok
color = 'anythingElse'; // Error
如果定义了两个相同名字的函数、接口或类,那么它们会合并成一个类型:
之前学习过,我们可以使用重载定义多个函数类型:
function reverse(x: number): number;
function reverse(x: string): string;
function reverse(x: number | string): number | string {
if (typeof x === 'number') {
return Number(x.toString().split('').reverse().join(''));
} else if (typeof x === 'string') {
return x.split('').reverse().join('');
}
}
接口中的属性在合并时会简单的合并到一个接口中:
interface Alarrm {
price: number
}
interface Alarm {
weight: number
}
相当于:
interface Alarm {
price: number;
weight: number;
}
注意,合并的属性的类型必须是唯一的:
interface Alarm {
price: number;
}
interface Alarm {
price: number; // 虽然重复了,但是类型都是 `number`,所以不会报错
weight: number;
}
interface Alarm {
price: number;
}
interface Alarm {
price: string; // 类型不一致,会报错
weight: number;
}
// index.ts(5,3): error TS2403: Subsequent variable declarations must have the same type. Variable 'price' must be of type 'number', but here has type 'string'.
接口中方法的合并,与函数的合并一样:
interface Alarm {
price: number;
alert(s: string): string;
}
interface Alarm {
weight: number;
alert(s: string, n: number): string;
}
相当于:
interface Alarm {
price: number;
weight: number;
alert(s: string): string;
alert(s: string, n: number): string;
}
类的合并与接口的合并规则一致。