#I'm not sure I understand unions.

28 messages · Page 1 of 1 (latest)

clear breach
#

I'm pretty new to typescript and working on converting some javascript into typescript. I have a lot of nearly-json-schema objects. I'm working on building out types so the schemas produce types and the schemas themselves are type checked. Which has me running into this bizarre behavior on unions.

interface Foo {
    type: StringConstructor,
    foo: string
}

interface Bar {
    type: BooleanConstructor,
    bar?: string
}

type TestType = Foo | Bar
const t1 : TestType = { type: String, foo: "hello" }
const t2 : TestType = { type: String } //Properly emits error here, foo is missing
const t3 : TestType = { type: Boolean, foo: "hello" } //Missing error here, foo does not exist in Bar
const t4 : Bar = { type: Boolean, foo: "hello" } //Properly produces error

I am truly baffled by type union behavior. Why does t3 not emit an error? The object it's being assigned is not shaped like a Foo nor a Bar. Attempting to assign the same object shape to a Bar will emit an error. VSCode's autocomplete also suggests foo in t3 as a valid property. Clearly I am missing something.

pulsar bluff
#

hmm

#

!pg

earnest peakBOT
pulsar bluff
#

!ts

earnest peakBOT
#
let x: StringConstructor = Boolean;
//  ^
// Type 'BooleanConstructor' is missing the following properties from type 'StringConstructor': fromCharCode, fromCodePoint, raw
pulsar bluff
#

very odd...

pulsar bluff
#

t3 is a Bar

clear breach
#

If t3 is a Bar, then t4 should not emit an error.

pulsar bluff
#

it's a bit weird but that's just how it is in TS

#

not quite sure what's the usecase of allowing this tbh

clear breach
#

It's runtime type shenanigans because TS also lacks reflection and type metadata

#
testSchema({
    config: {
        type: Object,
        properties: {
            num: { type: Number, template: true },
            str: { type: String },
        },
    },
    handle(config) {
        //config is type checked here based on the schema
        config.num = 10
        config.str = "Blah"
    },
})
pulsar bluff
#

no i mean allowing foo when it's a union

clear breach
#

OH

#

I guess I'm just trying to figure out if it's a bug or if it's intentional

#

It feels like a bug, but also I'm like a week into using TS. So crying compiler bug a couple days in is misguided

#

And I suppose if there's a work around to get it to emit an error.

pulsar bluff
#

is there a reason you can't use "boolean" instead of BooleanConstructor?

clear breach
#

because boolean is a type not a value and the schema objects exist at runtime

#

I do through more type schenanigans make sure the resulting type like config in that example are using boolean not Boolean

pulsar bluff
clear breach
#

It might be possible, but the end schema system expects constructors for custom types that aren't builtins

pulsar bluff
#

ah

clear breach