这两个初始化不应该等效吗?
这行得通:
private screensMap: Map<string, ComponentType<any>>;
public constructor() {
this.screensMap = new Map()
.set(BootstrapLaunch.name, BootstrapLaunch)
.set(BootstrapWelcome.name, BootstrapWelcome);
}
但这失败了:
private screensMap: Map<string, ComponentType<any>>;
public constructor() {
this.screensMap = new Map([
[BootstrapLaunch.name, BootstrapLaunch],
[BootstrapWelcome.name, BootstrapWelcome],
]);
}
出现下一个错误:
error TS2345: Argument of type '([string, typeof BootstrapLaunch] | [string, typeof BootstrapWelcome])[]' is not assignable to parameter of type 'ReadonlyArray<[string, typeof BootstrapLaunch]>'.
Type '[string, typeof BootstrapLaunch] | [string, typeof BootstrapWelcome]' is not assignable to type '[string, typeof BootstrapLaunch]'.
Type '[string, typeof BootstrapWelcome]' is not assignable to type '[string, typeof BootstrapLaunch]'.
Type 'typeof BootstrapWelcome' is not assignable to type 'typeof BootstrapLaunch'.
Type 'BootstrapWelcome' is not assignable to type 'BootstrapLaunch'.
Types of property 'componentDidMount' are incompatible.
Type '(() => void) | undefined' is not assignable to type '() => void'.
Type 'undefined' is not assignable to type '() => void'.
是Typescript错误还是我做错了什么?
答案 0 :(得分:0)
TypeScript试图推断您的值的类型,但是由于您的组件在实现componentDidMount
方面有所不同,因此它试图警告您可能的编程错误。
由于所需的值类型比提供的组件的类型宽,因此您可以使用类型参数告诉TypeScript您的意图是什么
public constructor() {
this.screensMap = new Map<string, ComponentType<any>>([
[BootstrapLaunch.name, BootstrapLaunch],
[BootstrapWelcome.name, BootstrapWelcome],
]);
}