代码之家  ›  专栏  ›  技术社区  ›  alexojegu

用Typescript中的数组初始化映射:新映射([[k1,v1],[k2,v2]]

  •  2
  • alexojegu  · 技术社区  · 7 年前

    这很好用:

    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'.
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   Karol Majewski    7 年前

    TypeScript试图推断值的类型,但由于组件在实现方面不同 componentDidMount ,它试图警告您可能的编程错误。

    由于所需的值类型比提供的组件类型更广泛,因此可以使用类型参数告诉TypeScript您的意图:

    public constructor() {
        this.screensMap = new Map<string, ComponentType<any>>([
            [BootstrapLaunch.name, BootstrapLaunch],
            [BootstrapWelcome.name, BootstrapWelcome],
        ]);
    }
    
    推荐文章