Skip to content

Instantly share code, notes, and snippets.

@mpvosseller
Created May 3, 2021 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpvosseller/b549c05b54d569ba3fe8e4211329cb4e to your computer and use it in GitHub Desktop.
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"
// 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