Home > Blockchain >  Confusing compiler error: Argument of type 'string' is not assignable to parameter of type
Confusing compiler error: Argument of type 'string' is not assignable to parameter of type

Time:11-16

I have an array with acceptable mime types:

export const frontend = { 
  ...
  zipMimeTypes: [
    "application/zip",
    "application/x-zip-compressed",
    "multipart/x-zip",
  ],
} as const;

I want to include it in another file and use it like so:

frontend.zipMimeTypes.includes(file.type)

However, my TS compiler is complaining about file.type

Argument of type 'string' is not assignable to parameter of type '"application/zip" | "application/x-zip-compressed" | "multipart/x-zip"'.

I just do:

  [
    "application/zip",
    "application/x-zip-compressed",
    "multipart/x-zip",
  ].includes(file.type)

It works

CodePudding user response:

The issue is in as const. Instead, you can define an interface to use with frontend:

interface Frontend {
  zipMimeTypes: string[];
}
const frontend: Frontend = {
  zipMimeTypes: [
    "application/zip",
    "application/x-zip-compressed",
    "multipart/x-zip"
  ]
};

CodePudding user response:

Although forcing zipMimeTypes to be a string array will get rid of the error, you have now lost your typing for zipMimeTypes.

Instead I would create a type for your zipMimeTypes.

The advantages is that code-completion works nicely too.

export const frontend = { 
  zipMimeTypes: [
    "application/zip",
    "application/x-zip-compressed",
    "multipart/x-zip",
  ],
} as const;

type zipMimeType = typeof frontend.zipMimeTypes[number];

interface File {
    type: zipMimeType;
}

const file:File = {
    type: 'application/zip'
}

if (frontend.zipMimeTypes.includes(file.type)) {
  //etc.
}

TS Playground

  • Related