关于“未知”用法的 TypeScript 3.0 错误

TypeScript 3.0 error on `unknown` usage

这里,我测试的是TypeScript3.0unkown类型。

https://blogs.msdn.microsoft.com/typescript/2018/07/12/announcing-typescript-3-0-rc/#the-unknown-type

TypeScript 3.0 introduces a new type called unknown that does exactly that. Much like any, any value is assignable to unknown; however, unlike any, you cannot access any properties on values with the type unknown, nor can you call/construct them. Furthermore, values of type unknown can only be assigned to unknown or any.

我玩了一些 Church eoncoding 东西,并测试了函数的每个参数的 unknown 类型,我有如下错误:

const log = (m: unknown) => {
    console.log(m); //IO
    return m;
};

const I = (x:unknown) => x;
const L = (x:unknown) => (y:unknown) => x;
const P = (x:unknown) => (y:unknown) => (z:Function) => z(x)(y);
//z is a binary operator Function!

const Left = L;
const Right = L(I);

log("Left Right test---------");
log(
    Left("boy")("girl")  // boy
);
log(
    Right("boy")("girl")  //TypeScript Type Error here
);

错误:

church.ts:20:9 - error TS2571: Object is of type 'unknown'.

20         Right("boy")("girl")
           ~~~~~~~~~~~~

以防万一,这在 vanilla JS 中经过了充分测试,但我只是想知道如何在不使用 any 类型的情况下解决此错误。

谢谢。

很简单,我认为您不应该使用 unknown 而应该使用通用函数,因为 L 的参数和最终的 return 类型之间存在明显的关系:

const I = (x:unknown) => x;
const L = <T>(x:T) => (y:unknown) => x;

const Left = L;
const Right = L(I); 

log("Left Right test---------");
log(
  Left("boy")("girl")  // boy
);
log(
  Right("boy")("girl")  //all ok 
);

我会像 any 一样使用 unknown 作为最后的手段类型,当类型不仅在编写函数时未知(我们可以使用常规类型)而且在调用时也是不可知的函数(这是我使用泛型类型参数的时候)。

如果出于某种原因泛型不可行,解决此问题的唯一方法是使用类型断言,因为您知道在这种情况下类型系统丢失的信息:

(Right("boy") as ((x:unknown)=> unknown))("girl")  //all ok