Narrowing(型の絞り込み)の話です。この記事で言いたかった事はもう全て言い終えました。残りは雑談コーナーです。
const narou = (message: string | null) => {
if (message === null) {
throw new Error('もう遅い')
}
return message
}
type NarouReturnType = ReturnType<typeof narou>
こういう時にNarouReturnTypeはstring | null
からstring
へNarrowingされます。
const narou = (message: { type: string | null; body: string }) => {
if (message.type === null) {
throw new Error('もう遅い')
}
return message
}
type NarouReturnType = ReturnType<typeof narou>
でもこの場合NarouReturnTypeは{ type: string; body: string }
になってくれたりはしません。{ type: string | null; body: string }
のままです。あくまで親オブジェクトの型としては1つなので子が絞り込まれようともそれによって新しい型は作ってくれないという事でしょうかね。親子といえど所詮他人。
const narou = (message: { type: string | null; body: string }) => {
if (message.type === null) {
throw new Error('もう遅い')
}
return { ...message, type: message.type }
}
type NarouReturnType = ReturnType<typeof narou>
こうするとNarouReturnTypeは{ type: string; body: string }
になってくれます。実装としても新しいオブジェクトを生成しているので、よろしい新しい型を作ってやろうという事でしょうか。
const narou = (message: { type: string; body: string } | { type: null; body: string }) => {
if (message.type === null) {
throw new Error('もう遅い')
}
return message
}
type NarouReturnType = ReturnType<typeof narou>
なおこの場合もNarrowingされます。以上、TS4.2.4からでした。