返回类型为info的动态对象属性

问题描述

我有以下问题:

getValue()函数可以很好地工作并获得所需的值。但是,在此过程中,类型信息会丢失,并且类型变为任意类型。

我知道如何使用类型转换解决此问题,但是如果可以通过类本身在类中完成此转换,那将是很好的。这可能吗?

class hi {
    five = 5;
    foo = '3';

    getValue(val: string) {
        // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'hi'.
        // No index signature with a parameter of type 'string' was found on type 'hi'
        return this[val]  // this will always return any because TS can infer the type
    }
}

const hey = new hi();

// I would like this type to be number by adding additional logic in the class
const numberFive = hey.getValue('five'); // type any

// I would like this type conversion to be handled in the class if this is possible
const numberFive2 = hey.getValue('five') as number; // type number 

解决方法

class Foo {
  five = 5;
  foo = '3';

  getValue<T extends keyof this>(val: T): this[T] {
    return this[val];
  }
}

const foo = new Foo();

const stringFoo = foo.getValue('foo');   // string
const numberFive = foo.getValue('five'); // number

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...