Skip to content

Instantly share code, notes, and snippets.

@lmiller1990
Last active December 21, 2020 02:26
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 lmiller1990/443ec2f875fb8612afb34677d3b1e993 to your computer and use it in GitHub Desktop.
Save lmiller1990/443ec2f875fb8612afb34677d3b1e993 to your computer and use it in GitHub Desktop.
How do I infer the return type of `getStyleValue`?
type StyleRule = 'color' | 'fontSize'
interface DefaultStyleSheet {
color: string
fontSize: number
}
export type PDFStyleSheet = Partial<DefaultStyleSheet>
const defaults: DefaultStyleSheet = {
color: 'black',
fontSize: 14
} as const
class Node {
styles: PDFStyleSheet
constructor(styles: PDFStyleSheet) {
this.styles = styles
}
}
const node = new Node({ color: 'red' })
function getStyleValue(
rule: StyleRule,
node: Node,
) {
if (rule in node.styles && node.styles[rule] !== undefined) {
return node.styles[rule]
}
if (rule in defaults && defaults[rule] !== undefined) {
return defaults[rule]
}
throw Error(`You forgot to declare a default for ${rule} in defaults.`)
}
// Infer c is a string
// why is return type string | number | undefined? I want it to infer c is a string.
const c = getStyleValue('color', node)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment