Typescript 中,interface 的类型为什么不能满足 Record<string, unknown> 类型?

146 阅读1分钟

我有一段代码,在调用函数的地方,由于涉及到 interface 和 unknown 导致传入参数的校验没能通过编译。
简化了一下,核心部分的代码如下:

interface Fail {
  readonly empty: any;
}
function validate(_input: Record<string, unknown>) {}
// Argument of type 'Fail' is not assignable to parameter of type 'Record<string, unknown>'.
//   Index signature for type 'string' is missing in type 'Fail'.  ts(2345)
validate({} as unknown as Fail);

自己测试了一下,发现有 2 种改动可以通过:

1.调用时不使用 interface

validate({} as unknown as { readonly empty: any; });
  1. 函数声明时,不使用 unknown 而使用 any
function validate(_input: Record<string, any>) { }

现在比较好奇:

  1. unknown 和 any 在这个 case 里有什么区别?
  2. interface 在这个 case 上又起了什么作用,它和直接用 ... as {} 的行为区别在哪?