Kou*_*sha 12 javascript promise typescript
如何设置拒绝承诺的类型?让我说我做:
const start = (): Promise<string> => {
return new Promise((resolve, reject) => {
if (someCondition) {
resolve('correct!');
} else {
reject(-1);
}
});
}
Run Code Online (Sandbox Code Playgroud)
假设我想拒绝一个数字.但我不能设置类型; 我可以把我想要的任何东西传给reject这里.
此外,在使用此承诺时,如果我错误地使用拒绝响应类型,我想要编译错误.
Est*_*ask 16
正如在解释这个问题,Promise没有不同类型的满足,拒绝承诺.reject 接受any不影响promise类型的参数.
目前Promise无法打字任何更好.这是因为承诺可以throw通过内部拒绝then或catch(这是拒绝现有承诺的一种可取方式),而这不能通过键入系统来处理; 另外,TypeScript也没有特殊于异常的类型never.
小智 7
因为在某些情况下无法设置错误类型,例如 Promise 或异常抛出,我们可以以类似 rust 的方式处理错误:
// Result<T, E> is the type used for returning and propagating errors.
// It is an sum type with the variants,
// Ok<T>, representing success and containing a value, and
// Err<E>, representing error and containing an error value.
export type Ok<T> = { _tag: "Ok"; ok: T };
export type Err<E> = { _tag: "Err"; err: E };
export type Result<T, E> = Ok<T> | Err<E>;
export const Result = Object.freeze({
Ok: <T, E>(ok: T): Result<T, E> => ({ _tag: "Ok", ok }),
Err: <T, E>(err: E): Result<T, E> => ({ _tag: "Err", err }),
});
const start = (): Promise<Result<string, number>> => {
return new Promise((resolve) => {
resolve(someCondition ? Result.Ok("correct!") : Result.Err(-1));
});
};
start().then((r) => {
switch (r._tag) {
case "Ok": {
console.log(`Ok { ${r.ok} }`);
break;
}
case "Err": {
console.log(`Err { ${r.err} }`);
break;
}
}
});
Run Code Online (Sandbox Code Playgroud)
这是我尝试输入的内容:
export class ErrPromise<TSuccess, TError> extends Promise<TSuccess> {
constructor(executor: (resolve: (value: TSuccess | PromiseLike<TSuccess>) => void, reject: (reason: TError) => void) => void) {
super(executor);
// Object.setPrototypeOf(this, new.target.prototype); // restore prototype chain
}
}
export interface ErrPromise<TSuccess, TError = unknown> {
then<TResult1 = TSuccess, TResult2 = never>(onfulfilled?: ((value: TSuccess) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: TError) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
catch<TResult = never>(onrejected?: ((reason: TError) => TResult | PromiseLike<TResult>) | undefined | null): Promise<TSuccess | TResult>;
}
Run Code Online (Sandbox Code Playgroud)
像平常一样使用它:
return new ErrPromise<T,ExecError>((resolve, reject) => { ... })
Run Code Online (Sandbox Code Playgroud)
您的 IDE 应选择以下类型reject:
| 归档时间: |
|
| 查看次数: |
5556 次 |
| 最近记录: |