![](/img/trans.png)
[英]How to pass an argument with multiple types as an argument to a function in Typescript?
[英]Typescript: Error on function argument when the function can be of multiple function types
我有以下示例代碼:
type GetMultipleFunction1 = () => Promise<string[]>;
type GetMultipleFunction2 = (data: number) => Promise<string[]>;
type GetMultipleFunction = GetMultipleFunction1 | GetMultipleFunction2;
function test(func: GetMultipleFunction): Promise<string[]> {
return func();
}
function getStrings(data: number): Promise<string[]> {
return new Promise(function (resolve, reject) {
resolve(['hello', 'hi']);
}) }
test(getStrings);
為什么會出現錯誤( return func()
第 6 行):
預期 1 個參數,但得到 0。
我覺得 GetMultipleFunction 可以是類型 1 或類型 2。類型 1 不需要參數。
我需要如何更改代碼才能消除警告?
問題出在這一行type GetMultipleFunction = GetMultipleFunction1 | GetMultipleFunction2;
type GetMultipleFunction = GetMultipleFunction1 | GetMultipleFunction2;
.
兩個函數的聯合永遠不會以您期望的方式運行。 它產生一個函數,其中參數是兩個函數參數的相交類型。 見小例子:
type Foo = (arg: { age: number }) => void
type Bar = (arg: { name: string }) => void
type Union = Foo | Bar
declare let func:Union
// let func: (arg: { age: number;} & { name: string;}) => void
func()
這是設計使然,這是調用函數聯合的最安全方法。
在你的例子中:
function test(func: GetMultipleFunction): Promise<string[]> {
return func(); // < ------ ERROR
}
調用func
最安全的方法是提供一個參數。 它將涵蓋兩種情況。 如果你傳遞了一個不需要參數的函數 - 它不會造成任何傷害。
我認為在這個例子中它值得使用函數交集而不是聯合。 像這兒:
type GetMultipleFunction1 = () => Promise<string[]>;
type GetMultipleFunction2 = (data: number) => Promise<string[]>;
export type GetMultipleFunction = GetMultipleFunction1 & GetMultipleFunction2;
function test(func: GetMultipleFunction): Promise<string[]> {
return func(); // no error
}
function getStrings(data: number): Promise<string[]> {
return new Promise(function (resolve, reject) {
resolve(['hello', 'hi']);
})
}
test(getStrings); // error
然而,我們在一個新的地方遇到了錯誤: test(getStrings); // error
test(getStrings); // error
。
這是因為Type '(data: number) => Promise<string[]>' is not assignable to type '() => Promise<string[]>'.
我很難猜測你在這里想要實現什么。 getStrings
data
參數未使用。
您還可以重載您的test
功能:
type GetMultipleFunction1 = () => Promise<string[]>;
type GetMultipleFunction2 = (data: number) => Promise<string[]>;
function test(func: GetMultipleFunction2): Promise<string[]>
function test(func: GetMultipleFunction1): Promise<string[]>
function test(func: (...args: any[]) => Promise<string[]>): Promise<string[]> {
return func(); // ok
}
function getStrings(data: number): Promise<string[]> {
return new Promise(function (resolve, reject) {
resolve(['hello', 'hi']);
})
}
test(getStrings); // ok
test(() => Promise.resolve(42)); // expected error
不要擔心我已經使用(...args: any[])
,測試函數仍然只接受GetMultipleFunction1
或GetMultipleFunction2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.