( English is not my mother language, please don’t mind my poor English 🙂 )
I have a folder that saves svgs for some technologies’ logo (React, Vue, etc.), and each of the filenames looks like [technology-name].svg
(React.svg, Vue.svg, etc.). So I used fs.readdir
to read the folder, then return the names as an array like ['React', 'Vue']
.
Now I want to extract the names as a union type (‘React’ | ‘Vue’) to get type support, but It seems not possible to do so. The ‘const’ assertion show me an error: “A ‘const’ assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals.”, but the type of SVGNames
is string[]
, it makes me confused.
import { readdir } from 'node:fs/promises'
import { cwd } from 'node:process'
const getSVGNames = async () => {
const fileNames = await readdir(`${cwd()}/public/svgs`)
const SVGNames = fileNames.map(fileName => {
const SVGName = fileName.split('.')[0]
return SVGName
})
return SVGNames as const
} // ^?const SVGNames: string[]
export {
getSVGNames
}
Since it didn’t work correctly as I thought, I saved the filename and its path manually. Now it looks like below:
const iconSet = {
Astro: "svgs/Astro.svg",
NodeJS: "svgs/NodeJS.svg",
React: "svgs/React.svg",
// ...
Solid: "svgs/Solid.svg",
TypeScript: "svgs/TypeScript.svg",
Vue: "svgs/Vue.svg",
};
When I have new logo to put in, I have to add key-value pair to the iconSet
manually, it is so repeating-my-self.
I saw a post from reddit, it said that it doesn’t seems possible to do so.
Could someone help? Highly appreciated!
ffxixslh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.