【发布时间】:2021-11-08 23:11:42
【问题描述】:
我在尝试推断函数 post 返回类型的类型时遇到了这个问题。它的第二个参数是一个具有transform 属性的对象。因此,如果提供了transform 参数,那么post 的返回类型应该是transform 的返回类型,否则为post 函数提供的第一个泛型类型。希望能被理解。
type DefautlHttpCallInit = {
throttle?: number;
baseUrl?: string;
url?: string;
onSend?(e: HttpCallInit) : void | Promise<void>;
}
export type HttpCallInit = RequestInit & DefautlHttpCallInit
export type HttpCallInitOf<T> = RequestInit & DefautlHttpCallInit & {
transform?: <TOut>(v: T) => TOut
};
export type HttpCallerInstance = {
post<T, TInit extends HttpCallInitOf<T>>(data?: T, init?: TInit): Promise<TInit extends {transform(e: T): infer XOut} ? XOut : T>;
}
//hack reference
let r = {} as HttpCallerInstance;
interface Post {
id?: number;
title: string;
}
interface User {
id: number;
userName: string;
}
interface UserPost extends Post{
user: User
}
const user = {/* info props */} as User;
r.post({title: 'New post'} as Post, {
//First: infer
transform(post) {
return Object.assign(post, {user}) as UserPost
}
})
编译器选项
{
"compilerOptions": {
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"noImplicitReturns": true,
"alwaysStrict": true,
"esModuleInterop": true,
"declaration": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"target": "Latest",
"module": "ESNext",
"moduleResolution": "node"
}
}
【问题讨论】:
标签: typescript