簡體   English   中英

TS 從對象參數的回調屬性的返回類型推斷

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM