Created
May 3, 2021 02:10
-
-
Save mpvosseller/b549c05b54d569ba3fe8e4211329cb4e to your computer and use it in GitHub Desktop.
UnknownMaybe: utility type that treats an object as "unknown but might be of type T"
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
// utility type that treats an object as "unknown but might be of type T" | |
// allows you to access each property that T has but assumes the value is `unknown | undefined` | |
// this lets you test the values of each property to determine if it is in fact a T | |
// autocomplete and refactoring the property names work | |
// you get a compiler error if you try to access a property not in T | |
type UnknownMaybe<T> = { | |
[P in keyof T]?: T[P] extends object ? UnknownMaybe<T[P]> : unknown | |
} | |
interface Message { | |
content: string | |
meta: { | |
timestamp: Date | |
} | |
} | |
function handle(msg: UnknownMaybe<Message>): void { | |
// if msg was just "unknown" you could not access any properties | |
if (typeof msg.content === 'string' && typeof msg.meta?.timestamp === 'string') { | |
// this is a valid Message | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment