Home > Enterprise >  Typescript - type assertion with invalid value is not throwing error
Typescript - type assertion with invalid value is not throwing error

Time:05-16

I have a type assertion for the variable 'day', because of this when I assign boolean for the key, it doesn't throw any error.

I am not doing like this const day: Day = 2 because the value I get is a string (which is a dynamic value) and I need to do a type assertion.

Could you please check this below example and suggest what needs to be changed to make it throw an error?

    type Day = 0 | 1 | 2;

type TTime = {
    [K in Day]?: string
}

const day = 2 as Day;

const obj: TTime = {
    [day]: true // Expect this to throw error as 'boolean is not assignable to key
}

Another detailed example of what I am trying to resolve. I have to get the keys of another object(which is by default string[]) and do type assertion.

type Day = 0 | 1 | 2;

type TTime = {
    [K in Day]?: string
}

const result: TTime = {
    2: 'I am result'
}

const keys = Object.keys(result);

let obj: TTime;
keys.forEach((key) => {
    const k = key as unknown as Day;
    const value = result[k]; //Key is string, so needs to be type asserted
    obj = {
        [k]: true //k is 2 in this case, but the value is boolean type and incorrect, this error
                  // is thrown when I remove the type assertion added and hardcode k as 2.
    }
})

CodePudding user response:

this way the error will show up;


type Day = 0 | 1 | 2;

type TTime = {
    [K in Day]?: string
}

const day: Day = 2;

const obj: TTime = {
    [day]: true // Expect this to throw error as 'boolean is not assignable to key
}

CodePudding user response:

The type assertion on day is causing the issue. You don't need an assertion (or even an annotation): primitives are immutable in JavaScript and TypeScript, so by declaring the variable using the const keyword, the number will always be the literal type 2, and TypeScript knows this without additional syntax.

TS Playground

type Day = 0 | 1 | 2;

type TTime = { [K in Day]?: string };

// This is the same type as above, using some type utilities:
// https://www.typescriptlang.org/docs/handbook/utility-types.html
// type TTime = Partial<Record<Day, string>>;

// Don't use a type assertion here. (https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions)
// If you prefer an annotation, you could write it this way:
// const day: Day = 2;
const day = 2;

const obj: TTime = {
  [day]: true, /*
  ~~~~~
  Type of computed property's value is 'boolean', which is not assignable to type 'string'.(2418) */
};

  • Related