So I'm stuck on a (confusing for me) situation, any help would be greatly appreciated:
I have some big objects with different types of properties. I'm using generics and iterating through the fields to render inputs based on the field's type. Ex text field for string, checkbox for bool, and so on.
Some of the fields could be null, so I can't just use typeof on the actual value, which means I have to create a type schema for the JS, which is feeling super redundant and not very DRY, just to create the inputs ex:
interface Data {
foo: string
bar: number
baz: Date
}
const dataTypes = {
foo: "string",
bar: "number",
baz: "Date"
}
It's a long shot, but I guess my question is: can I use the Typescript type in the JavaScript logic? Ex:
if ( typescript-typeof val == "boolean | null" ) drawCheckbox()
Thank you for any help!
=== EDIT === Example of when JS doesn't know the type:
interface Obj {
foo: string | null
bar: number | null
baz: Date | null
}
const obj: Obj = {
foo: "abc",
bar: null,
baz: new Date()
}
function drawInput(val: Obj[keyof Obj]) {
switch (typeof val) {
case "string": drawTextField()
case "boolean": drawCheckbox()
case "object": // originally a string, boolean, or Date?
}
}
=== EDIT #2 only way I know how to make it work--- with redundant code ===
interface Obj {
foo: string | null,
bar: boolean | null,
baz: Date | null
}
const objTypes: {[key in keyof Obj]: string} = {
foo: "string",
bar: "boolean",
baz: "Date"
}
const obj: Obj = {
foo: "abc",
bar: null,
baz: new Date()
}
function drawInput <K extends keyof Obj>(key: K, val: Obj[K]) {
switch (objTypes[key]) {
case "string": drawTextField(val)
case "boolean": drawCheckbox(val)
case "Date": drawDatePicker(val)
case "object": // will never happen now
}
}
typeof value === 'boolean' || value === null? What's so special about the Typescript type? And no, they only exist at compile time.