1

I am having custom types defined like this

export type Extensions =
  | '.gif'
  | '.png'
  | '.jpeg'
  | '.jpg'
  | '.svg'
  | '.txt'
  | '.jpg'
  | '.csv'
  | '.zip';

export type mimeType = 'image' | 'application' | 'text';

export type FileType = {
  [key in mimeType]?: Extensions[];
};

When used in a function i get the following error , Type 'string' is not assignable to type 'mimeType'. While destructuring i am giving the type as [mimeType, Extensions[]] but still it is throwing the above error. Can someone help me?

Here is my usage when destructuring it

export const getAcceptedFileTypes = (mimeTypes: FileType) => {
  const acceptedTypes: Accept = {};
  Object.entries(mimeTypes).forEach(([key, extensions]: [mimeType, Extensions[]]) => {
    if (key === 'text') {
      acceptedTypes['text/*'] = extensions;
    } else if (key === 'image') {
      extensions.forEach(
        (image) => (acceptedTypes[`image/${image.substring(1)}`] = [image])
      );
    } else {
      extensions.forEach(
        (application) =>
          (acceptedTypes[`application/${application.substring(1)}`] = [
            application,
          ])
      );
    }
  });
  return acceptedTypes;
};
1

1 Answer 1

0

This is the type definition of the Object.entries function:

entries<T>(o: { [s: string]: T } | ArrayLike<T>): [string, T][];

You can see that the tuple in the return type always has the first element to be string and it's independent on the input. You'll have to convert it to the required type:

(Object.entries(mimeTypes) as [mimeType, Extensions[]][]).forEach(...)

You'll not have to give the type again in the forEach callback

Sign up to request clarification or add additional context in comments.

3 Comments

thanks . One more quick question, can I have the only restricted items when a mimeType is selected, say if mimeType is text i extensions should just be csv, txt
you can setup an object type that maps mimetype -> allowed types and use that instead of the Extension[]. If you need more explanation, please ask another question, since it doesn't have much to do with the current one

Your Answer

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