Repository navigation
Enable literal type access to MIME types in Typescript - #339
Conversation
- Enable literal types on the type map object so that MIME types are accessible in Typescript.
- Preserve type safety of `{[key: string]: string}` using Typescript `satisfies`
- Enable literal types on the type map object so that MIME types are accessible in Typescript.
- Preserve type safety of `{[key: string]: string}` using Typescript `satisfies`
|
Hi Matt, thanks for the PR. Can you give me an example or two of how this is useful? I'm not familiar with |
|
Hi Robert, No worries, of course. 1. The problem and what this PR fixesAs this was explicitly typed as Take the following example: function checkMIMEType(file: File, type: string) {
return file.type === type;
}I could use this function as follows: checkMIMEType(someFile, "text/xml");However, it would be extremely useful if I could use a literal type for the ❌ We don't want to allow: checkMIMEType(someFile, "some string") // ⚠️ Would always be false because the type parameter isn't a MIME type
checkMIMEType(someFile, "txt/xml") // ⚠️ Would always be false as there is a typo in the MIME type (type parameter)✅ Instead, we want to allow: checkMIMEType(someFile, "text/xml"); // ✅ since "text/xml" is a valid MIME type in the databaseGiven this library, I wouldn't want to create my own database of possible MIME types, so the solution should be: import standardTypes from "mime/types/standard.ts";
type MIMEType = keyof typeof standardTypes; // ✅ MIMEType must be one of the keys in the database
function checkMIMEType(file: File, type: MIMEType) { // 🎉 `type` is not just any old string anymore
return file.type === type;
}What this PR solves is that, where the type was set to So now: checkMIMEType(someFile, "some string");
// ❌ Before: Typescript would allow, because "some string" is a string
// ✅ After: Typescript will not allow, because "some string" isn't one of the MIME types
checkMIMEType(someFile, "txt/xml");
// ❌ Before: Typescript would allow, because "txt/xml" is a string
// ✅ After: Typescript will not allow, because "txt/xml" isn't one of the MIME types
checkMIMEType(someFile, "text/xml");
// ⚠️ Before: Typescript would allow, because "text/xml" **is a string**
// ✅ After: Typescript will allow because "text/xml" **is recognised as a MIME type**This was not possible before. 2. Maintaining the type safety of the database (
|
|
Great explanation, thank you. So... next question: Is this a semver "patch", "minor", or "major" (breaking) change? (I'm tempted to say it should be major because it changes the TS api types in a way that may break |
|
I would say this is a minor update per the SemVer spec. 😁 My reasoning:
|
|
Published as Thanks for the contribution. I particularly appreciate the time you took to explain everything. 👍 |
|
You’re welcome. Happy to help and great to see it merged! 😁🎉 |


{[key: string]: string}using Typescriptsatisfies.