我在 TS 中使用类型注释作为某种文档。对我来说,很高兴知道我的函数将预先管理的类型。
我还没有找到一种方法来声明这种函数的类型。编译器推断出一个类型,但是当我尝试自己用相同的类型进行注释时,它会崩溃。
以这个函数为例:
// compiler infers the type
// f: ({ a }?: { a?: number | undefined }) => number
const f = ({ a = 0 } = {}) => a;
但是当我尝试注释它失败并出现以下错误。
const f: ({ a }?: { a?: number | undefined }) => number =
({ a = 0 } = {}) => a;
// ^
// \-- Property 'a' does not exist on type '{ a?: number | undefined; } | undefined'