0

My goal is to have an object with attributes part of a typescript string enum.

type PARAM = "long-parameter" | "long-parameter2";

const PARAM = {
    param1: "long-parameter" as PARAM,
    param2: "long-parameter2" as PARAM,
}

var f = function(params:{[id:PARAM]:number}){}

f({ //must be valid
    [PARAM.param1]:1,
});

f({ //should display error
    "asdas":1
});

The problem is that var f = function(params:{[id:PARAM]:number}){} returns the error An index signature parameter type must be string or number.

Is there any way around that?

1 Answer 1

1

The key for an index signature must be a string or a number. This just because of how JavaScript works (everything is converted to a string in an object member lookup).

If you know the names of the member you should really declare them up front. This is shown below:

type PARAM = "long-parameter" | "long-parameter2";

const PARAM = {
    param1: "long-parameter" as PARAM,
    param2: "long-parameter2" as PARAM,
}

var f = function(params: { "long-parameter"?: PARAM, "long-parameter2"?: PARAM }) { }

f({ //must be valid
    [PARAM.param1]: 1,
});

f({ //should display error
    "asdas": 1
});

Tested with alm:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

How does the valid assignment work - 1 is not the string value long-parameter or long-parameter2 but the values for the interface are set to PARAM ... why does f({[PARAM.param1]: 1}) successfully compile?

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.