简体   繁体   中英

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

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

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"
  ]
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM