本人TS不是很懂,今天看到这样的代码export type Service<T, P extends any[]> = (...args: P) => Promise<T>;
对Promise<T> 这个写法不是很理解。另外总觉得Ts里像这种复杂的定义一眼很难理解,对代码的可读性是不是有些影响?
这叫泛型。
我们来看一个 Promise 方法:
var options = {
method: "POST"
url: "/api",
data: {
id: 1
}
};
fakeRequestAsync(options)
.then((res) => {
console.log(res.data);
});
fakeRequestAsync
是一个 Promise 方法,它有参数 options
,有 .then
的回调参数 res
。
再看 TS 声明:
Service<T, P extends any[]> = (...args: P) => Promise<T>
T
就是上面的 res
,P
就是上面的 options
。
Promive<T>
是 ES2015 自带类型,在 TS 标准库中就有。你可以在 VSCode 里按住 Ctrl+左键,点击这个类型,就能跳转到标准库的声明文件了,你可以看下微软是怎么声明它的。