[英]Typescript: How to define a type for a callback that shouldn't return anything?
我的意思是它應該返回undefined
或根本不返回。 典型的安全回調。
試用一:
declare const fn1: (cb: () => void) => void;
fn1(() => '123'); // no error
哎呀。 它沒有成功。 string
適用於void
。 好的...
試訓2:
declare const fn2: (cb: () => unknown) => void;
fn2(() => '123'); // no error
哎呀。 相同。 哎呀。
試訓3:
declare const fn3: (cb: () => undefined) => void;
fn3(() => '123'); // error: Type 'string' is not assignable to type 'undefined'
很好,好的:go 與它:
fn3(() => undefined); // okay
fn3(() => {}); // error: Type 'void' is not assignable to type 'undefined'
嗯。 這不是我要找的。
好吧,這個瘋狂的想法是怎么回事? 試訓4:
declare const fn4: (cb: () => void | undefined) => void;
fn4(() => undefined); // okay
fn4(() => { }); // okay
fn4(() => '123'); // error: Type 'string' is not assignable to type 'undefined'
哇。 這就是我想要的。
但它看起來像一個骯臟的黑客。 為什么在地球上void
不抱怨string
,而是void | undefined
void | undefined
嗎? 這是一個錯誤嗎?
我可以依靠這種行為嗎? 它不會在某些未來版本的 TS 中修復嗎? 有沒有更好的方法來完成同樣的事情?
更新 2
一個不應該有任何參數的回調,甚至是可選的,也不應該返回任何東西,應該像這樣定義:
type callback = (...a: void[]) => void | undefined;
const func = (a: callback) => {
a();
};
const test1 = func(() => { }); // works
const test2 = func((a?: string) => { }); // fails
const test2 = func(() => '5'); // fails
更新
在評論中討論后發現目標是獲得一個回調而不是忽略返回,但保證它不會返回任何其他內容,並且它可以傳遞給基於返回值改變行為的其他函數。
在這種情況下,我建議添加一個真正忽略任何返回值的小助手 function。
const shutUp = <T extends (...args: any) => void>(func: T): ((...args: Parameters<T>) => void) => (...args: any[]) => {
func(...args);
};
const shutUpNoArgs = <T extends () => void>(func: T): ((...args: never) => void) => () => {
func();
};
const test = shutUp((a: string) => 5);
const r1 = test('5'); // works, r1 is void.
const r2 = test(5); // doesn't work.
_.forEach(data, shutUp(callback));
原來的
你不應該那么嚴格,也不必為此擔心太多。
void
意味着我們不關心回報,如果我們不依賴它,我們應該嗎?
這與說我們不接受 function 是一樣的,因為它不需要我們a
參數,盡管它可以處理這種情況。
declare const fn1: (cb: (a: string) => void) => void;
fn1(() => {
}); // no error even we don't have `a` in our callback.
文檔: https://www.typescriptlang.org/docs/handbook/basic-types.html#void
void
有點像any
的對立面:根本沒有任何類型。
因此,它的行為不會改變,您可以在undefined
的聯合中使用它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.