typescript - 條件函數類型
給定以下情境,
function doSomething({ id, name, onSelect, onUnselect }: TDoSomething) {
if (onSelect) {
// I want `onUnselect` to be defined here
// ...
}
return { id, name }
}
type TDoSomething =
| IDoSomethingWithoutSelect
| IDoSomethingWithSelect
interface IDoSomethingWithoutSelect {
id: string
name: string
}
interface IDoSomethingWithSelect {
id: string
name: string
onSelect: (id: string) => void
onUnselect: (id: string) => void
}
我想做的事情(概念上?)很簡單:如果定義了 onSelect,則 onUnselect 必須也被定義。換句話說,如果我傳入 onSelect,那麼這個函數也必須預期有一個 onUnselect。
(這裡可以進入你的遊樂場。)
結果發現我的努力都是失敗的。我不確定我應該做什麼才能取得成功。
(這是我嘗試過的其他事情)
答案#1
你可以使用 in 運算子將參數類型縮小為 IDoSomethingWithSelect
function doSomething(arg: TDoSomething) {
const { id, name } = arg;
if ('onSelect' in arg) {
arg.onUnselect(id);
}
return { id, name }
}
