Whycan'taninterfacebeassignedtoRecord<string,unknown>?

I just noticed that an interface cannot be assigned to Record<string, unknown> (playground link):

interface Foo {
    foo: number
}

const foo: Foo = { foo: 1 }
const bar: Record<string, unknown> = foo
//    |-> Error: Type 'Foo' is not assignable to type 'Record<string, unknown>'
//               Index signature is missing in type 'Foo'.(2322)

However the same is possible, when the type declaration for Foo is omitted (playground link):

const foo = { foo: 1 }
const bar: Record<string, unknown> = foo // no error here

Question: Why is there a difference between both examples? For me the reduced type of the variable foo is the same in both examples... Shouldn't the interface Foo be assignable to Record<string, unknwon>?!

In my understanding Record<string, unknown> is equivalent to object and thus any interface should be assignable to it. Also https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/ban-types.md suggests using Record<string, unknown> instead of object.

Remarks: The first example works when either object (playground link) or Record<string, any> (playground link) is used instead of Record<string, unknown>.

回答

您遇到过类型中缺少索引签名(仅在接口上,而不是在类型别名上)#15300

当您将接口更改为类型时,代码将起作用:

type Foo = {
    foo: number
}

const foo: Foo = { foo: 1 };
const bar: Record<string, unknown> = foo;


以上是Whycan'taninterfacebeassignedtoRecord&lt;string,unknown&gt;?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>