0

I made this simple code:

const testHashMap = {
    hello: "Hi",
    test: "Hey",
    blabla: "Halo"
}

const inputFromField : string = "hello";

alert(testHashMap[inputFromField]);

But the last line doesn't work because it demands that inputFromField will be from type "hello" | "test" | "blabla" and not a general string, how can I insist to use string? as it should be an input from the user in the future.

1 Answer 1

1

You can explicitly declare the type for your constant:

const testHashMap: Record<string, string> = {
    hello: "Hi",
    test: "Hey",
    blabla: "Halo"
}

Record<string,string> is a more readeable form (syntactic sugar?) for {[key: string]: string}. You could have written the code above like this and it would mean the same:

const testHashMap: {[key: string]: string} = {
    hello: "Hi",
    test: "Hey",
    blabla: "Halo"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Just from curiosity, could you show how it would be done without the Record interface?

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.