为什么记录中会“丢失”某个任意键<string,any>?

问题描述 投票:0回答:1

考虑:

let a:Record<string,any> = {data:"hello"}; //valid
let b:{data:string} = a; //Property 'data' is missing in type 'Record<string, any>' but required in type '{ data: string; }'

Record 的意义不就是指定某项具有 K 类型的键和 T 类型的值吗?断言特定记录具有某些键如何违反此规定?

我知道我可以将该属性设为可选:

let b:{data?:string} = a; //valid

为什么不应该假定更具体的 {stringkeyname:any} 类型与 Record 兼容?

[编辑以删除对类型断言的无关引用]

typescript
1个回答
0
投票

Typescript 是在 JS (VALUE) 空间上添加的 TYPE 空间。

Typescript 在类型空间中运行。当您使用类型注释初始化 var 时,该 var 将具有此注释类型,而不是分配的 VALUE 类型:

let a:Record<string,any> = {data:"hello"}; // {data: 'hello'} doesn't affect the type space

然后您尝试将

Record<string, any>
类型分配给
{date: string}
并出现错误,因为
Record<string, any>
不一定包含
{date: string
:

let b:{data:string} = a; // not compatible

另一方面,当您省略类型注释时,var 的类型是从值空间推断的,并且

{date: string}
可分配给
Record<string, any>

let a = {data:"hello"};
let b:Record<string,any> = a; // OK!
© www.soinside.com 2019 - 2024. All rights reserved.