#How to safely access a static property from a specific instance?

5 messages · Page 1 of 1 (latest)

lofty creek
#

Accessing foo.constructor.staticProp gives me Property 'staticProp' does not exist on type 'Function', but it's valid JS -- what's the way to do this safely in typescript without ts-ignoring the complaint?

In this example I specifically know the type, but in a real case I won't always know the type, but I do know that it will have a type static variable

boreal jewelBOT
#
claudekennilol#0

Preview:```ts
console.clear()
const log = console.log

class Foo {
public static readonly type = "static property"
}

const foo = new Foo()

log(foo.constructor.type)```

leaden quest
#

@lofty creek constructor isn't typed in TS on purpose; I'd personally really look for some other pattern (e.g. attaching the property to the instance)

#

I think you can explicitly specify the constructor type:

class Foo {
    public static readonly type = 'static property';
}
// modify the Foo type to specify the constructor field
interface Foo {
    constructor: typeof Foo;
}

but I'm not sure this is actually a good idea

lofty creek
#

I can't attach the property to the instance. The library I'm using requires this static property. This is what I've got for now which is mostly fine since I'm only using it in tests to print out the type name when performing a single test against a collection of these objects

    const getStaticType = (obj: object) => {
        const ctor = obj.constructor as unknown as { type: string };
        return ctor.type;
    };