除了 Promise 之外还有什么对象吗?

Mar*_*lom 7 typescript

有没有办法指定函数接受Promise 之外的任何对象作为参数?

(我希望编译器能够捕获丢失的“await”关键字。)

art*_*tem 6

是的,有点像。有一个技巧可以通过使用可选的void类型声明这些属性来禁止具有某些属性的对象类型:

type NotAPromise<T> = T & { then?: void };

function f<T>(o: NotAPromise<T>) {
}

f(1); // ok
f({}); // ok 


f(Promise.resolve(2)); 

Argument of type 'Promise<number>' is not assignable to parameter of type 'NotAPromise<Promise<number>>'.
  Type 'Promise<number>' is not assignable to type '{ then?: void | undefined; }'.
    Types of property 'then' are incompatible.
      Type '<TResult1 = number, TResult2 = never>(onfulfilled?: ((value: number) => TResult1 | PromiseLike<TResult1>) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike<...>) | null | undefined) => Promise<...>' is not assignable to type 'void'.
Run Code Online (Sandbox Code Playgroud)