1

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

2 Answers 2

3

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"
  ]
};
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.