簡體   English   中英

打字稿使用參數類型推斷與默認值

[英]Typescript use parameter type inference with defaults

我有如下功能,效果很好:

function pickAttributes<K extends string, T> (e: Element, attrs: K[]): Record<K, string> {
  return attrs.reduce((obj, key) => {
    return {
      ...(obj as any),
      [key]: e.getAttribute(key)
    }
  }, {})
}

我希望該函數可以使用可選的map函數將屬性轉換為其他類型。

function pickAttributes<K extends string, T> (e: Element, attrs: K[], mapFn?: (attr: null | string) => T): Record<K, T> {
  if (!mapFn) mapFn = x => String(x)
  return attrs.reduce((obj, key) => {
    return {
      ...(obj as any),
      [key]: mapFn(e.getAttribute(key))
    }
  }, {})
}

但是我得到這個錯誤

TS2322: 
Type '(x: string | null) => string' is not assignable to type '((attr: string | null) => T) | undefined'. 
  Type '(x: string | null) => string' is not assignable to type '(attr: string | null) => T'.
     Type 'string' is not assignable to type 'T'.

如果我嘗試使用默認參數,則會收到類似的錯誤。

更改后的功能似乎可以正常運行,而無需嘗試添加默認值

function pickAttributes<K extends string, T> (e: Element, attrs: K[], mapFn?: (attr: null | string) => T): Record<K, T> {
  return attrs.reduce((obj, key) => {
    return {
      ...(obj as any),
      [key]: e.getAttribute(key)
    }
  }, {})
}

首先:我不確定什么可以擴展字符串,所以我將刪除通用參數K。

但是無論如何:您希望您的返回類型根據mapFn參數的存在而變化。 我將通過定義函數的兩個重載來解決這一問題。 並且在實現中,通過使用聯合類型string | T string | T

function pickAttributes<K extends string>(e: Element, attrs: K[]): Record<K, string>;
function pickAttributes<K extends string, T> (e: Element, attrs: K[], mapFn: (attr: null | string) => T): Record<K, T>;
function pickAttributes<K extends string, T> (e: Element, attrs: K[], mapFn?: (attr: null | string) => T): Record<K, string | T> {
  const fn = mapFn || (x => String(x));
  return attrs.reduce((obj, key) => {
    return {
      ...(obj as any),
      [key]: fn(e.getAttribute(key))
    }
  }, {});
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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