[英]TS infer from return type of callback property of an object parameter
我在嘗試推斷函數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" } }
您將泛型TOut
指定為轉換本身的泛型,但這不是它所代表的,方法或函數上的泛型決定了它被調用時的行為。 您想在聲明中指定轉換輸出類型(與T
位於同一位置),然后將其指定為post
函數的泛型, 如下所示:
export type HttpCallInitOf<T, TransformedType = unknown> = RequestInit & DefautlHttpCallInit & {
transform?: (v: T) => TransformedType
};
export type HttpCallerInstance = {
post<T, TransformedType = T>(data?: T, init?: HttpCallInitOf<T,TransformedType>): Promise<TransformedType>;
// TransformedType is defaults to T so if it can't be infered it stays as T
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.