jmls
jmls

Reputation: 2969

using an object property as a type in typescript

I have a third party piece of code that is defined as this

export const Actions = {
  findByIdAccessTokens: class implements Action {
            public readonly type = UserActionTypes.FIND_BY_ID_ACCESSTOKENS;
            public payload: { id: any; fk: any; customHeaders };

            constructor(
                id: any,
                fk: any,
                customHeaders?: Function,
                public meta?: any
            ) {
                this.payload = { id, fk, customHeaders };
            }
        },
}

in my code I want to pass in a parameter that has a type of findByIdAccessTokens

however, I can't seem to find a way of being able to tell the compiler that my parameter is of that type

so, for example

import { Actions,ActionTypes } from '@base/sdk/actions'; 
...
filter((action:Actions.findByIdAccessTokens) => 

gives the error [ts] Cannot find namespace 'Actions'.

I've tried every combination that I can think if, and unfortunately my google search terms are so generic (class, typed, etc) that I cannot find any article that solves the problem

I know if I define and export a class

export class findByIdAccessTokens implements Action {
        public readonly type = UserActionTypes.FIND_BY_ID_ACCESSTOKENS;
        public payload: { id: any; fk: any; customHeaders };

        constructor(
            id: any,
            fk: any,
            customHeaders?: Function,
            public meta?: any
        ) {
            this.payload = { id, fk, customHeaders };
        }
    },

and import that directly, then

import { updateByIdAccessTokensSuccess } from '@base/sdk/actions';
...
filter((action:findByIdAccessTokens) => 

compiles just fine (along with the type safety)

Upvotes: 1

Views: 50

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250326

You can use a type query to get the class, you are close but you need to use typeof to get the type of the constant :

let findByIdAccessTokens: typeof Actions.findByIdAccessTokens; // findByIdAccessTokens is the class (not an instance of the class)
new findByIdAccessTokens(/*...*/ ) // Add parameters

If you need the instance type for the class you can use the InstanceType conditional type

let findByIdAccessTokens!: InstanceType< typeof Actions.findByIdAccessTokens>; // findByIdAccessTokens is the instance of the class
findByIdAccessTokens.type // we can access properties

Upvotes: 1

Related Questions