typescript类型深入

ts类型深入

new(…args: any[]) => T

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import "reflect-metadata";

const Service = (): ClassDecorator => {
return target => {
// [ [Function: Bar], [Function: String] ]
console.log(Reflect.getMetadata('design:paramtypes', target));
};
};

class Bar { }

@Service()
class Foo {
constructor(bar: Bar, baz: string) { }
}

// 相当于创建一个匿名类,然后new出一个对象a。
let a = new class {
hello() {
console.log('ddd');
}
}

a.hello();

tsc 编译后。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var Bar = /** @class */ (function () {
function Bar() {
}
return Bar;
}());
var Foo = /** @class */ (function () {
function Foo(bar, baz) {
}
Foo = __decorate([
Service(),
__metadata("design:paramtypes", [Bar, String])
], Foo);
return Foo;
}());
var a = new /** @class */ (function () {
function class_1() {
}
class_1.prototype.hello = function () {
console.log('ddd');
};
return class_1;
}());
a.hello();

类的类型。

this is a class named class

class Person {}

let p = new Peson()

p的类型是Person

Person的类型是 new(…args: any[]) => Person

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Person {
walk() {
console.log('walk');
}
}

// 定义一个类型。
interface Type<T> {
new(...args: any[]): T;
}

let b = new class {
hello<T>(target: Type<any>): T {
console.log(target); // [Function: Person]
return new target();
}
}
let c = b.hello<Person>(Person);
c.walk();

let d: Type<Person> = Person;
console.log(d) // [Function: Person]
console.log(Person) // [Function: Person]
console.log(new Person()) // Person {}



// 定义一个类型
export type GenericClassDecorator<T> = (target: T) => void;

const Service1 = (): GenericClassDecorator<Type<any>> => {
return (target: Type<any>) => {
// do something with `target`, e.g. some kind of validation or passing it to the Injector and store them
};
};