【问题标题】:Any Object except Promise?除了 Promise 之外的任何对象?
【发布时间】:2017-01-25 02:24:14
【问题描述】:

有没有办法指定一个函数接受任何对象除了一个Promise作为参数?

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

    type NotAPromise = { then?: void };
    
    function f(o: NotAPromise) {
    }
    
    f(1); // ok
    f({}); // ok 
    
    
    f(Promise.resolve(2)); 
    
    Argument of type 'Promise<number>' is not assignable to parameter of type 'NotAPromise'.
      Types of property 'then' are incompatible.
        Type '{ (onfulfilled?: (value: number) => number | PromiseLike<number>, onrejected?: (reason: any) => n...' is not assignable to type 'void'.
    

    这是相当粗糙的,因为它会拒绝像这样的有效的非承诺

    f({ then: 42 });
    

    如果这成为问题,您可以尝试这样声明

    type NotAPromise = { then?: NotAFunction };
    

    NotAFunction 来自this answer

    【讨论】:

      猜你喜欢
      • 2017-11-15
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多