【发布时间】:2021-09-22 15:50:38
【问题描述】:
由于下面显示的错误,以下示例无法编译(在最后两行)。
import { Subject } from 'rxjs';
class Example<T> {
readonly events = new Subject<T>();
constructor(x: T) { }
}
// ...
let example: Example<unknown>;
// ...
example = new Example('some string');
// ...
example = new Example(123);
错误:
Type 'Example<string>' is not assignable to type 'Example<unknown>'.
Types of property 'events' are incompatible.
Type 'Subject<string>' is not assignable to type 'Subject<unknown>'.
Types of property 'observers' are incompatible.
Type 'Observer<string>[]' is not assignable to type 'Observer<unknown>[]'.
Type 'Observer<string>' is not assignable to type 'Observer<unknown>'.
Type 'unknown' is not assignable to type 'string'.ts(2322)
我看到此错误的项目使用的是 Typescript 4.3.5 版和 RxJs 6.5.5 版。只有在 tsconfig.json 中启用了 strict 标志时,才会发生该错误。
我不明白为什么我会看到这个错误。错误消息中的每一行(最后一行除外)对我来说都不是错误,因为它表示将具体类型分配给未知类型,这是一个有效的分配。对于最后一行 (Type 'unknown' is not assignable to type 'string'),我知道将 unknown 分配给 string 会出错,但我看不到这样的分配发生在哪里。
代码示例有什么问题?
编辑
我还注意到,如果我删除 Example 类中的 events 属性,错误就会消失。
【问题讨论】:
-
你自己输入的是未知的,这行
let example: Example<unknown>;。只需将unknown更改为string -
请注意,这是一个缩小范围的示例。我无法将
unknown更改为string,因为代码的其他部分可能会将不同类型的Example分配给example。我编辑了我的问题以使其更清楚。
标签: typescript rxjs