這個問題在這里已經有了答案: TypeScript 條件回傳值型別? (1 個回答) 9 小時前關閉。
我有一個函式,它接受 2 個引數,根據第二個引數的值回傳一個字串|未定義或緩沖區|未定義。
const readAsync = (path:string, returnAs?:"utf8"|"buffer") => {
const data = await FileSystem.readAsBuffer(path);
if (!data) return undefined; //Returns undefined
if (returnAs === "buffer") return data; //Returns buffer
return Buffer.from(data).toString(); //Returns a string
}
如果第二個引數未指定或為“utf8”,則結果應為 Promise<string|undefined>,但如果引數為“buffer”,則回傳型別應為 Promise<Buffer|undefined>。
但是,我得到的回傳型別是 Promise<string|Buffer|undefined>,這不是我想要的。
uj5u.com熱心網友回復:
這是使用函式多載簽名的情況:
async function readAsync (path: string, returnAs?: 'utf8'): Promise<string | undefined>;
async function readAsync (path: string, returnAs: 'buffer'): Promise<Buffer | undefined>;
async function readAsync (path: string, returnAs?: 'utf8' | 'buffer') {
// implementation of function
}
const result1 = readAsync('path'); // Promise<string | undefined>
const result2 = readAsync('path', 'utf8'); // Promise<string | undefined>
const result3 = readAsync('path', 'buffer'); // Promise<Buffer | undefined>
uj5u.com熱心網友回復:
這可能通過泛型實作,但即使是這樣,我認為它也會很丑陋。如果可能的話,我會以這種方式解決問題:
const readToBufferAsync(path: string): Promise<Buffer> => {
const data = await FileSystem.readAsBuffer(path);
if (!data) { return undefined; }
}
const readToStringAsync(path: string): Promise<string> {
const buffer = await readToBufferAsync(path);
return Buffer.from(data).toString();
}
您通常希望避免使用字串型別的解決方案,例如將選項或標志作為字串傳遞給函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409683.html
標籤:
上一篇:打字稿修改或擴展呼叫簽名
