TS interface doesn’t recognize fx properties when they’re set within the function itself

  Kiến thức lập trình

I’m trying to to use ts to declare a factory function that also has a property on the function itself (meant to simulate a static property of sorts). I use an interface to do this.

interface MyFunc {
    (): object
    staticData: object
}

The problem is that I’m setting the property of the function within the function itself like so:

const Func1: MyFunc = () => {
    Func1.staticData = {data1: 1, data2: 2}
    return {
        staticData: Func1.staticData
    }
}

But ts gives the error: Property ‘staticData’ is missing in type ‘() => { staticData: object; }’ but required in type ‘MyFunc’.

I can fix this by adding the staticData after the function is declared, but then the return object from the function no longer gets access to it.

const Func1: MyFunc = () => {
    return {
        staticString: {data1: 1, data2: 2} //loses ability to refer to static value now
    }
}
Func1.staticString = {data1: 1, data2: 2} //fixes warning

Is there a way to fix the interface for this function so that I can keep my first way of doing it and not have ts throw an error.

LEAVE A COMMENT