我有一段代码,在调用函数的地方,由于涉及到 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; });
- 函数声明时,不使用
unknown
而使用any
function validate(_input: Record<string, any>) { }
现在比较好奇:
unknown
和any
在这个 case 里有什么区别?interface
在这个 case 上又起了什么作用,它和直接用... as {}
的行为区别在哪?