jeshio
jeshio

Reputation: 665

How to reusing class constructor argument as literal string with TypeScript?

How I can do this?

type Module = {
    created: number;
}

class Example {
    constructor(
        public readonly moduleName: string
    ) { }

    getModule = (modules: {
        [this.moduleName]: Module // <-- property error
    }) => modules[this.moduleName]
}

property error is "A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type."

The playground is here

Upvotes: 0

Views: 203

Answers (1)

Josh Wulf
Josh Wulf

Reputation: 4877

Is this what you are tryna do?

type Module = {
    created: number;
}

class Test<T extends string> {
    constructor(
        public readonly moduleName: T
    ) { }

    getModule = (modules: {
        [key: string]: Module
    }): Module => modules[this.moduleName]
}

You are trying to mix static typing with dynamic assembly at run-time. Without giving the type system information about possible values, like ModuleNames as a string literal discriminated union, there little it can tell you about what this is doing at run-time.

It looks like this object will take a keyed object of modules, and return from that "its own module".

Like this:

type Module = {
    created: number;
}

interface ModuleCache { [key: string]: Module }

class Test<T extends string> {
    constructor(
        public readonly moduleName: T
    ) { }

    getModule = (modules: ModuleCache): Module =>
        modules[this.moduleName]
}

Upvotes: 1

Related Questions