Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Typescript 基于类型化约束的类型脚本推理_Typescript - Fatal编程技术网

Typescript 基于类型化约束的类型脚本推理

Typescript 基于类型化约束的类型脚本推理,typescript,Typescript,我有一些描述Api调用的类型。例如: export class RequestType { prop1: string; prop2: string; } export class ResponseType { prop3: string; prop4: string; } 每个请求类型都链接到一个响应类型。我目前正在做的是定义一个接口IReturn,并将其添加到请求类型: export interface IReturn<T> {} export class

我有一些描述Api调用的类型。例如:

export class RequestType {
  prop1: string;
  prop2: string;
}

export class ResponseType {
  prop3: string;
  prop4: string;
}
每个请求类型都链接到一个响应类型。我目前正在做的是定义一个接口
IReturn
,并将其添加到请求类型:

export interface IReturn<T> {}

export class RequestType implements IReturn<ResponseType> {
  prop1: string;
  prop2: string;
}
import { RequestType, IReturn } from './dto';

export class SomeService {
    callApi<TRequest extends IReturn<TResponse>, TResponse>(dto: Request) TResponse {
      // implementation
    }
}

我现在有点不知所措。我如何重构服务、接口或DTO以获得请求和响应类型的类型推断?

这里有几个问题,第一个问题是您有未使用的泛型参数,因为typescript使用的是结构类型系统,这些参数几乎被忽略。您可以在下面的文档中看到这一点。第二个问题是,当
TRequest扩展IReturn
时,typescript不会进行类型推断来猜测
treresponse
,它只会选择最简单的
treresponse
,通常是
{}

// response is a {} and not a ResponseType!!
const response = this.someService.call(requestInstance);
为了克服这些限制,我们可以首先使用
IReturn
中的type参数,例如,我们可以有一个表示
T
构造函数的字段(但实际上任何用法都可以,即使是伪用法,也可以说
\u unusedField:T
)。对于第二个问题,我们可以使用条件类型从
IReturn
中提取
T

导出类响应类型{
prop3:字符串;
prop4:字符串;
}
导出接口IReturn{returnCtor:new(…args:any[])=>T;}
导出类RequestType实现IReturn{
returnCtor=ResponseType;
prop1!:字符串;
prop2!:字符串;
}
导出类服务{

callApi什么是
TreResponse
callApi
的想法是我将参数约束为TRequest,TRequest必须是
IReturn
TreResponse
是第二个通用参数,应该解析为
ResponseType
。我愿意接受所有可能的选择:我想要的是一个“知道”如果我传递一个
RequestType
返回的类型应该是
ResponseType
。这个想法是正确的。谢谢!谢谢你的推断,我不知道。但是,如果我在VS code中复制代码,
response
被猜测为
{}
。我在TS 2.9.1上。它对你有效吗?奇怪……如果我将代码复制到另一个文件中,它会有效。可能是我这边有冲突。将问题标记为已解决!你就是那个人!@A.Chiesa是的,添加了游乐场链接作为证据:)
export class ResponseType {
    prop3: string;
    prop4: string;
}

export interface IReturn<T> { returnCtor : new (...args: any[] ) => T; }

export class RequestType implements IReturn<ResponseType> {
    returnCtor = ResponseType;
    prop1!: string;
    prop2!: string;
}

export class SomeService {
    callApi<TRequest extends IReturn<any>>(dto: TRequest) : TRequest extends IReturn<infer U> ? U : never {
        return null as any
    }
}

const someService = new SomeService;
const requestInstance = new RequestType;
const response = someService.callApi(requestInstance);