我有以下类和函数:
class Test {
prop: string;
otherProp: number;
constructor() {
const result = doSomething<Test>('prop');
}
}
function doSomething<T>(propName: keyof T): ???? {
// ,,,
}
有一种使用 typescript 的方法,我可以从函数返回与函数获取的属性相同的类型。在上面的例子中,返回类型应该是string
。如果我用 otherProp
调用它,返回类型应该是数字。
最佳答案
您需要一个额外的类型参数来捕获传入的键的实际类型(我们称之为K
。然后您可以使用K
索引到 T
(即使用类型查询)
class Test {
prop: string;
otherProp: number;
constructor() {
const result = doSomething(this, 'prop');
}
}
function doSomething<T, K extends keyof T>(target: T, propName: keyof T): T[K] {
return this[propName];
}
我修改了上面的示例以传递一些类型为 T
的参数,以从参数中推断出 K
和 T
。 Typescript 不支持部分类型推断,因此我们无法指定 T
并推断出 K
。所以如果我们没有 T
类型的参数,我们需要这样写:
class Test {
prop: string;
otherProp: number;
constructor() {
const result = doSomething<Test, 'prop'>('prop');
}
}
function doSomething<T, K extends keyof T>(propName: keyof T): T[K] {
return this[propName];
}
一个更好的版本 s 使用函数 taht 返回一个函数,并在第一次调用中固定 T
并在第二次调用中推断出 K
:
class Test {
prop: string;
otherProp: number;
constructor() {
const result = doSomething<Test>()('prop');
}
}
function doSomething<T>() {
return function <K extends keyof T>(propName: keyof T): T[K] {
return this[propName];
}
}
关于基于类属性的 typescript 函数返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54365283/