首页 > 解决方案 > 从对象中获取项目没有错误

问题描述

有这个代码:

enum Stages { 
  BOOT = 'boot', 
  LOAD = 'load' 
}

interface A { … }
interface C<T> { … }

interface List {
  readonly [Stages.BOOT]: C<A>;
  readonly [Stages.LOAD]: C<A>;
}

class Main {
  constructor(
    readonly list: List
  ){}

  getItem <T extends A>(key: Stages): C<T> | null {
    if (key in this.list) return this.list[key] as C<T>; //here is the error
                               //^^^^^^^^^^^^^
    return null;
  }
}

编译器说:

Element implicitly has an 'any' type because expression of type 
 'Stages' can't be used to index type 'List'.
Property '[Stages.LOAD]' does not exist on type 'List'

但是该项目存在,记录该对象显示正确的行为。这里有什么问题?

标签: typescriptenums

解决方案


推荐阅读