0

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

1 Answer 1

1

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]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.