Home > Software engineering >  Typescript check for base class
Typescript check for base class

Time:05-24

I need to pass a class to handler in the object down below:

import { S01Handler } from "./handlers/start/S01Handler"


const config: ConfigInterface = {
    states: {
        [StateEnum.S01]: {
            objects: [
                BackgroundObject.NAME,
                LeavesObject.NAME,
            ],
            handler: S01Handler,
        },
    },
}

S01Handler extends an abstract base class BaseHandler. For example say export abstract class BaseClass {}

I want type-checking for BaseClass in handler entries.

My current ConfigInterface is not compatible for checking class types.

type StateEnum = import("./StateEnum").StateEnum
type BaseHandler = import("../handlers/BaseHandler").BaseHandler
type ObjectName = string & {readonly '': unique symbol}


interface ConfigInterface
{
    states: {
        [key in StateEnum]: {
            objects: ObjectName[]
            handler: BaseHandler // I believe this checks for instance?
        }
    }
}

How should I change this to achieve handler type-checking?

CodePudding user response:

I'm not 100% sure of your question, but in your code you have the comment "I believe this checks for instance?" here:

interface ConfigInterface
{
    states: {
        [key in StateEnum]: {
            objects: ObjectName[]
            handler: BaseHandler // I believe this checks for instance?
        }
    }
}

That comment is correct, it looks for an instance of BaseHandler. If you wanted to look for BaseHandler itself (the constructor function) or something that subclasses it, that would be typeof BaseHandler:

interface ConfigInterface
{
    states: {
        [key in StateEnum]: {
            objects: ObjectName[]
            handler: typeof BaseHandler
        }
    }
}
  • Related