📝
TypeScriptでResult<T>を実装
すでに存在していたら教えてください
2021.06.21追記
少しシンプルになりました
🙌 https://twitter.com/SubaruG/status/1406869743894634496?s=20
要件
- TSCがTの型チェックをしてくれること
- succeededの場合はT, failedの場合はErrorのメンバにアクセスできること
実装
export type ResultType<T> = ResultSucceeded<T> | ResultFailed
export class ResultSucceeded<T> {
public readonly resultType = "succeeded"
public constructor(public readonly value: T) { }
}
export class ResultFailed<T> {
public readonly resultType = "failed"
public constructor(public readonly error: Error) { }
}
使用
function someTest(arg: string): ResultType<string> {
if (arg.length > 0) {
return new ResultSucceeded("ok")
} else {
return new ResultFailed(new Error("Empty argument"))
}
}
const result = someTest("...")
switch (result.resultType) {
case "suceeded":
console.log(`Succeeded! ${result.value}`)
break
case "failed":
console.log(`Failed (T.T) ${result.error}`)
break
}
Discussion
このトピック
functional-programming
からなら、いろいろ見つかるかと思います。neverthrowライブラリから提供されているResult型を使ってデモ作ってみました。
簡単ですが、以上です。