gpt4 book ai didi

typescript 通用参数未正确解析

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:43 25 4
gpt4 key购买 nike

考虑一下,一个泛型类

export class Query<TResult> {
}

该类型的扩展类

export class ListSomeNumbersQuery extends Query<number[]> {
constructor() {
super();
}
}

访客类

class CqsClient {
executeQuery<TResult>(query: Query<TResult>): TResult {
//TODO: implement
}
}

用法

var result = client.executeQuery(new ListSomeNumbersQuery());

Visual Studio IDE 不理解结果是一个数字数组。怎么了?

编辑:Anders Hejlsberg 的选择非常有趣,Typescript 是一种类型删除语言,因此泛型只是编译时语法糖。但是添加私有(private)属性确实有效

export class Query<TResult> {
private _dummy: TResult;
}

最佳答案

发生这种情况是因为您没有在 Query 类中使​​用类型变量 TResult

来自 Docs :

When inferring the type of T in the function call, we try to find members of type T on the x argument to figure out what T should be. Because there are no members which use T, there is nothing to infer from, so we return {}.

如果你把它改成

export class Query<TResult> {
private result: TResult;
}

它将正确地将结果识别为 number[] 而不是 {}

关于 typescript 通用参数未正确解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com