簡體   English   中英

在指定其他類型時,如何讓 TypeScript 推斷受限泛型類型的值?

[英]How can I have TypeScript infer the value for a constrained generic type when specifying additional types?

在 TypeScript 中,我有一個 function 接受帶有約束的通用參數:

function f1<U extends string>(param: U): U {
  return param;
}

const a1 = f1('hello');
// a1's type is 'hello' -- Great!

現在,我正在嘗試這樣做,以便您可以選擇添加另一種類型作為返回類型的一部分。 但是,當我這樣做時,我必須為 U 類型提供一個默認參數。 這使得 TypeScript 停止推斷 U 的值並使用我提供的默認類型:

function f2<T = never, U extends string = string>(param: U): U | T {
  return param;
}

const b1 = f2('hello');
// b1's type is 'hello' -- Great!

const b2 = f2<boolean>('hello');
// b2's type is string | boolean -- Terrible: I want the type to be 'hello' | boolean.

const b3 = f2<boolean, 'hello'>('hello');
// b3's type is 'hello' | boolean -- Poor: The type is correct but API is redundant.

所以我的問題是,有沒有辦法讓 TypeScript 繼續從參數推斷類型 我不想為 U 提供默認類型,我總是希望 TypeScript 推斷該值。 顯示我想要的完整 API 的偽代碼:

function f3<T = never, U extends string = infer>(param: U): U | T {
  return param;
}

const c1 = f3('hello');
// c1's type is 'hello' -- Great!

const c2 = f3<boolean>('hello');
// c2's type is 'hello' | boolean -- Great!

不幸的是,這是不可能的。 有一個PR可以使用_ sigil 添加部分推理,但它已經有一段時間不活動了。

唯一的解決方案是使用 function currying 來獲得這種行為,盡管它並不理想:

function f2<T = never>() {
  return function <U extends string = string>(param: U): U | T {
    return param;
  }
}
const b2 = f2<boolean>()('hello');
// b2's type is string | 'hello' 

游樂場鏈接

暫無
暫無

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

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