Question:
Type inference with 'as const' IN TypeScript

Error:

Type '{ type: string; }' is not assignable to type 'ImageFormat'.


  Types of property 'type' are incompatible.


    Type 'string' is not assignable to type '"image/avif" | "image/jpeg" | "image/png" | "image/svg+xml" | "image/webp"'.ts(2322)


type.ts(5, 30): The expected type comes from property 'format' which is declared here on type '{ format: ImageFormat; }'


The above error might occur because const format = { type: 'image/png' } is inferred as { type: string; } per default and type: string is not specific enough to be assignable to the type Union in ImageFormat.


A const-assertion helps here because it forces TypeScript to infer the narrowest possible type which will be the literal string 'image/png'. That way { format } is assignable to the functions return type.


Arguably it's better to just assert to ImageFormat since the literal type information you get with as const will be lost anyway after returning from the function:


type ImageFormat = {

  type: 'image/avif' | 'image/jpeg' | 'image/png' | 'image/svg+xml' | 'image/webp';

};


const sampleFunction = (): { format: ImageFormat } => {

  const typedFormat: ImageFormat = {

    type: 'image/png',

  };

const format = {

   ...typedFormat,

   type: 'image/png' as ImageFormat["type"]

};

  return {

    format,

  };

};


Suggested blogs:

>Why Typescript does not allow a union type in an array?

>Narrow SomeType vs SomeType[]

>Create a function that convert a dynamic Json to a formula in Typescript

>How to destroy a custom object within the use Effect hook in TypeScript?

>How to type the values of an object into a spreadsheet in TypeScript?

>Type key of record in a self-referential manner in TypeScript?

>How to get the last cell with data for a given column in TypeScript?

>Ignore requests by interceptors based on request content in TypeScript?

>Create data with Typescript Sequelize model without passing in an id?

>How to delete duplicate names from Array in Typescript?


Nisha Patel

Nisha Patel

Submit
0 Answers