简体   繁体   English

为什么子类型分配和常规分配之间的错误不同?

[英]Why is the error different between subtype assignments and regular assignments?

sample code is below, I am checked by TypeScript playground https://www.typescriptlang.org/play/示例代码如下,我检查了 TypeScript 操场https://www.typescriptlang.org/play/

interface PartialCustomData {
    option?: number;
}

interface A {
    [key: string]: string | PartialCustomData;
}

interface B extends A {
    [key: string]: string | PartialCustomData | {[key: string]: string};
}

// this is no error
const b: B = { key1: 'a', key2: {b: 'b'}};
const a: A = b;

// this is error
const _a: A = { key1: 'a', key2: {b: 'b'}}

in this case, const a: A = b;在这种情况下, const a: A = b; is no error.没有错误。 but const _a: A = { key1: 'a', key2: {b: 'b'}} is error.但是const _a: A = { key1: 'a', key2: {b: 'b'}}是错误的。

error is below错误如下

Type '{ b: string; }' is not assignable to type 'string | PartialCustomData'.
  Object literal may only specify known properties, and 'b' does not exist in type 'PartialCustomData'.(2322)
input.ts(6, 5): The expected type comes from this index signature.

Why doesn't error occur at const a: A = b;为什么const a: A = b; ? ?

The problem is that {[key: string]: string} is assignable to PartialCustomData as an empty object {} (it fits {option?: number} ) and typescript considers them as the same type.问题是{[key: string]: string}可以作为空的 object {}分配给PartialCustomData (它适合{option?: number} )并且 typescript 将它们视为同一类型。

Long story short - it's a bug of typescript.长话短说 - 这是 typescript 的错误。

With option it would be a better example有了option ,这将是一个更好的例子

// this is no error
const b: B = { key1: 'a', key2: {option: 'b'}}; // works
const a: A = b;

// this is error
const _a: A = { key1: 'a', key2: {option: 'b'}}; // fails 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM