【问题标题】:Is there 'not promise' type in typescipt?打字稿中是否有“不承诺”类型?
【发布时间】:2019-09-16 07:03:58
【问题描述】:

我正在编写 TypeScript,并想创建类似 Exclude<void, Promise<void>> 的东西,它允许 void 但不允许 Promise<void>

type A = (a: number) => Promise<void>
type B = (a: number) => void

declare let a: A
declare let b: B
// it does not cause type error
b = a

// what i want to do...
// but it is identical to B
type C = (a: number) => Exclude<void, Promise<void>>

但是,Exclude&lt;void,Promise&lt;void&gt;&gt; 似乎与 void 相同。

有没有一些方法可以创建这样的类型?

【问题讨论】:

    标签: typescript types promise void


    【解决方案1】:

    正如TypeScript documentation 所说:

    void 有点像any 的反面:根本没有任何类型。

    由于没有任何类型,因此从其中排除某些东西是没有意义的。

    之所以可以将类型A 分配给类型B 的原因是,简单地说,只要忽略返回类型,任何函数都可以是void。因为void 的返回类型本质上意味着您不能使用返回值。而且这个属性与任何函数都兼容,你只需要忽略它返回的任何东西。

    这不仅会影响Promise&lt;void&gt;,还会影响所有返回类型:

    declare let voidFunction: (a: number) => void;
    declare let promiseFunction: (a: number) => Promise<void>;
    declare let numberFunction: (a: number) => number;
    declare let stringFunction: (a: number) => string;
    declare let undefinedFunction: (a: number) => undefined;
    
    voidFunction = promiseFunction; // no error
    voidFunction = numberFunction; // no error
    voidFunction = stringFunction; // no error
    voidFunction = undefinedFunction; // no error
    

    但是,请注意,事实并非如此:

    promiseFunction = voidFunction; // error
    numberFunction = voidFunction; // error
    stringFunction = voidFunction; // error
    undefinedFunction = voidFunction; // error
    

    我认为对您的情况更好的解决方案实际上是使用undefined 作为返回类型而不是void

    undefinedFunction = promiseFunction; // error
    undefinedFunction = numberFunction; // error
    undefinedFunction = stringFunction; // error
    

    但问题在于,当您声明一个返回类型为 undefined 的函数时,您实际上需要有一个 return undefined; 语句,而您可能不希望这样做。

    为了解决这个问题,我相信undefined | void 将是返回类型的一个很好的折衷方案:

    declare let undefinedVoidFunction: (a: number) => undefined | void;
    
    undefinedVoidFunction = promiseFunction // error
    undefinedVoidFunction = numberFunction // error
    undefinedVoidFunction = stringFunction // error
    
    undefinedVoidFunction = undefinedFunction // no error
    undefinedVoidFunction = voidFunction // no error
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-16
      • 1970-01-01
      • 2019-04-25
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2020-05-08
      相关资源
      最近更新 更多