Nicc
Nicc

Reputation: 777

Issue in Typing a class with Flowjs

I have the following code that I'm attempting to type with Flow

type Metadata = {
   currentPage: string,
};
type State = {
    result: {
        metadata: Metadata,
    }
}

type EmptyObject = {};
type Test = Metadata | EmptyObject;

class HelperFn {
    state: State;
    metadata: Test;
    constructor(state: State) {
        this.state = state;

        if (state && state.result && state.result.metadata) {
            this.metadata = state.result.metadata;
        } else {
            this.metadata = {};
        }
    }
    getCurrentPageNumber() {
        return this.metadata.currentPage;
    }
}

I've created Types that I'm assigning later on. In my class, I assign the type Test to metadata. Metadata can be either an object with properties or an empty object. When declaring the function getCurrentPageNumber, the linter Flow tells me that it

cannot get 'this.metadata.currentPage' because property 'currentPage' is missing in EmptyObject

Looks like Flow only refers to the emptyObject. What is the correct syntax to tell Flow that my object can either be with properties or just empty?

Upvotes: 0

Views: 53

Answers (1)

foxes
foxes

Reputation: 856

Since metaData can be empty, Flow is correctly telling you that this.metadata.currentPage may not exist. You could wrap it in some sort of check like

if (this.metadata.currentPage) {
    return this.metadata.currentPage
} else {
    return 0;
}

To get it to work properly.

Upvotes: 1

Related Questions