Created
July 12, 2022 09:41
-
-
Save mmitou/2ffc8ce6660be61a48747ff31b5a3b3c to your computer and use it in GitHub Desktop.
型の違う関数をキーで呼び分けたい時の処理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ErrorMessageTemplate = { | |
ElementNotFoundError({ elementId }: { elementId: string }) { | |
return `element not found: elementId=${elementId}`; | |
}, | |
UserNotFoundError({ userId }: { userId: string }) { | |
return `user not found: userId=${userId}`; | |
}, | |
}; | |
export class AppError< | |
K extends keyof typeof ErrorMessageTemplate | |
> extends Error { | |
constructor( | |
public readonly functionName: string, | |
public readonly name: K, | |
public readonly value: Parameters<typeof ErrorMessageTemplate[K]>[0], | |
public readonly cause?: Error | |
) { | |
const template = ErrorMessageTemplate[name] as ( | |
arg: Parameters<typeof ErrorMessageTemplate[K]>[0] | |
) => string; | |
super(template(value)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
genericsだけで全部解決しようとしたが出来なかった。
関数内でキャストして問題を回避した。