There are different types categorized based on mimetypes that I am currently working with.
export type MimeType = 'image' | 'application' | 'text';
export type ApplicationMimeType = '.pdf' | '.zip';
export type ImageMimeType = '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg';
export type TextType = '.csv' | '.txt';
export type ExtensionTypes = ImageMimeType[] | ApplicationMimeType[] | TextType[];
export type FileType = {
image?: ImageMimeType[];
application? : ApplicationMimeType[];
text? : TextType[]
};
When utilizing it in a function and passing a certain object, the key type defaults to string. Is there a way to have this key correspond to the type of MimeType?
I attempted the solution provided at this link: Typescript Key-Value relation preserving Object.entries type
The code snippet I used is giving me the error message
Type 'undefined' is not assignable to type 'string[]'
.
How can I constrain the key to be MimeType
and extensions to be ExtensionTypes
export type Entries<T> = {
[K in keyof T]: [extensions: T[K]][];
}[keyof T][];
export const getAcceptedFileTypes = (mimeTypes: FileType) => {
const acceptedTypes = {};
Object.entries(mimeTypes as Entries<mimeTypes>).forEach(([key, 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;
};
getAcceptedFileTypes({ image: ['.png'], application: [] })
tsconfig
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"jsx": "react-jsx",
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.lib.json"
},
{
"path": "./tsconfig.spec.json"
},
{
"path": "./.storybook/tsconfig.json"
}
]
}