簡體   English   中英

Typescript 函數的聯合/交叉類型

[英]Typescript union/intersection types for functions

當我有不同數量的參數和返回類型時,我試圖了解如何指定類型(對於函數)。

這個 function 可以:

  • 取 2 個 arguments(一個是可選的)並返回一個 Promise
  • 取2個arguments(第二個是回調)
  • 取3個arguments(第三個是回調)

讓我們首先為 3 種情況定義 3 種類型:

type Func1 = (a: string, b?: number) => Promise<void>;
type Func2 = (a: string, b: () => void) => void;
type Func3 = (a: string, c: number, b: () => void) => void;

現在我想定義一個包含這 3 個的類型。我讀到您應該對 function 類型使用交集。

type MultiFunction = Func1 & Func2 & Func3;

const f1: MultiFunction = async (a: string, b: number) => {};
const f2: MultiFunction = (a: string, b: () => void) => {};
const f3: MultiFunction = (a: string, c: number, b: () => void) => {};

f1("foo", 3);
f2("foo", () => {});
f3("foo", 3, () => {});

但是這里有一個聲明錯誤:

Type '(a: string, b: number) => Promise<void>' is not assignable to type 'MultiFunction'.
  Type '(a: string, b: number) => Promise<void>' is not assignable to type 'Func2'.
    Types of parameters 'b' and 'b' are incompatible.
      Type '() => void' is not assignable to type 'number'.ts(2322)

const f1: MultiFunction

如果我使用聯合:

type MultiFunction = Func1 | Func2 | Func3;

const f1: MultiFunction = async (a: string, b: number) => {};
const f2: MultiFunction = (a: string, b: () => void) => {};
const f3: MultiFunction = (a: string, c: number, b: () => void) => {};

f1("foo", 3);
f2("foo", () => {});
f3("foo", 3, () => {});

我在f1("foo", 3);上收到錯誤消息

Expected 3 arguments, but got 2.ts(2554)

types_test.ts(3, 37): An argument for 'b' was not provided.

我的問題是,處理這個(和類似的)案例的正確方法是什么?

像這樣使用function 重載

function func(a: string, b?: number):Promise<void>;
function func(a: string, b: () => void): void;
function func(a: string, c: number, b: () => void): void
function func(a: string, b?: any, c?: any): any {

}

func("foo", 3);
// interpreted as
// function func(a: string, b?: number | undefined): Promise<void>

func("foo", () => {});
// interpreted as
// function func(a: string, b: () => void): void

func("foo", 3, () => {});
// interpreted as
// function func(a: string, c: number, b: () => void): void

TS游樂場鏈接: https://tsplay.dev/WoJnLm

暫無
暫無

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

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