Home > Mobile >  Why Typescript sometimes doesn't allow to set value if it's structurally compatible with t
Why Typescript sometimes doesn't allow to set value if it's structurally compatible with t

Time:12-02

TypeScript is using structural typing and that's fine, but I noticed that it sometimes complains when there is no difference structurally. Why does it happen? What's going on here?

Example:

enum TagType {
    SIMPLE = 'simple',
    COLLECTOR = 'collector',
}

interface CollectorTag {
    type: TagType.COLLECTOR,
}

const tag1_1: CollectorTag = {
  type: TagType.COLLECTOR,
};

const tag1_2 = tag1_1;


const tag2_1 = {
  type: TagType.COLLECTOR,
};

const tag2_2: CollectorTag = tag2_1;
      ^^^^^^
      Error here

Playground Link

CodePudding user response:

Because those types are not really compatible tag2_1.tag can be any TagType, while tag1_1.tag is a specific value of the enum TagType.COLLECTOR.

Literal value types exist in typescript, meaning that a value can act as a type and only the specific value is assignable to such a literal value type. They are usually useful with unions

Using as const will make typescript infer tag2_1.tag as the literal type too


const tag2_1 = {
  type: TagType.COLLECTOR,
} as const;
const tag2_2: CollectorTag = tag2_1;

Playground Link

  • Related