返回类型为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