4
interface CustomResponse {
    data: string;
    status: number;
    [key: string]: string | number;
}

const RESPONSE_PROPS = {
  DATA: "data",
  STATUS: "status",
};

const response: CustomResponse = {
    data: "test",
    status: 200,
};

let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;

dataWrong gets the error

Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'

In cases like above, how to get dataWrong infer right type in typescript? Is type assertion (better type guards) the only way?

1 Answer 1

2

RESPONSE_PROPS.DATA is typed as string if you use an as const assertion (which will make the compiler keep the string literal type "data" for RESPONSE_PROPS.DATA) it works as expected:

interface CustomResponse {
    data: string;
    status: number;
    // [key: string]: string | number; not necessary for the code to work
}

const RESPONSE_PROPS = {
    DATA: "data",
    STATUS: "status",
} as const;

const response: CustomResponse = {
    data: "test",
    status: 200,
};

let dataWrong: string = response[RESPONSE_PROPS.DATA];
let dataRight: string = response.data;

Note: If the string literal type is used to index you don't really need the index signature.

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

3 Comments

Wow this worked.. May I get some doc reference/article on this const type inference?

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.