簡體   English   中英

返回類型取決於泛型的 Typescript 函數

[英]Typescript function whose return type depends on a generic

我正在嘗試編寫一個函數,其返回類型取決於通用參數。 下面是一段代碼來演示:

type FOOBAR = 'foo' | 'bar';

function fn<T extends FOOBAR>(arg: T): T extends 'foo' ? 'r1' : 'r2' {
  if (arg === 'foo') {
    return 'r1';
  }
  return 'r2';

}

const fooResponse = fn('foo'); // this is correctly typed as 'r1'
const barResponse = fn('bar'); // this is correctly typed as 'r2'

在函數體內,我看到Type '"r1"' is not assignable to type 'T extends "foo"? "r1": "r2"'. Type '"r1"' is not assignable to type 'T extends "foo"? "r1": "r2"'. . 我不清楚如何解決此投訴。

我確實看到了許多相關問題,但沒有一個解決依賴返回類型與聯合類型的組合問題。 我能找到的最接近的是 this ,這似乎暗示它目前是不可能的,盡管我不太確定。

您可以使用函數重載:

type FOOBAR = 'foo' | 'bar';

function fn(arg: 'foo'): 'r1';
function fn(arg: 'bar'): 'r2';
function fn(arg: FOOBAR) {
  if (arg === 'foo') {
    return 'r1';
  }
  return 'r2';
}

const fooResponse = fn('foo'); // this is correctly typed as 'r1'
const barResponse = fn('bar'); // this is correctly typed as 'r2'

暫無
暫無

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

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