Last active
December 21, 2020 02:26
-
-
Save lmiller1990/443ec2f875fb8612afb34677d3b1e993 to your computer and use it in GitHub Desktop.
How do I infer the return type of `getStyleValue`?
This file contains 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
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