Этот вопрос посвящен хорошему решению для типовойписнойпис для управления всеми вашими путями в вашей структуре файловой системы. class = "lang-ts prettyprint-override">const paths = {
data: {
settings: "settings.json",
translations: "translations/",
translationList: "translations.msgpack",
},
}
initPaths(paths)
// concat "settings.json" etc. with a base dir path
function initPaths(p: typeof paths) {
const dir = await appDataDir() // the data dir on local machine
for (const key in p.data) {
p.data[key] = resolve(dir, p.data[key])
}
}
Выше просто, просто сделайте paths.data.settings , и вы получаете путь. Позже я обнаружил, что большинство файлов и каталогов вложены в структурированную форму (вот в чем делают папки, верно?), Поэтому я разработал его для соединения путей в вложенных объектах.paths -> content -> pages)
// example paths that I'm trying to get
// "./"
// "./content"
// "./content/pages/Hello World!/attachments"
// "./auth.json"
const self = ""
export const paths = {
self,
content: {
self,
pages: {
self,
any: {
self,
attachments: { self },
files: { self },
},
},
},
auth: "auth.json",
}
// concat the paths of the nested objects recursively...
function resolvePath(
paths: Record,
base: string = "/path/to/root/dir",
) {
for (const key in paths) {
const t = typeof paths[key]
if (t === "object") {
let dirPath: string
if (key === "any") {
dirPath = "."
} else {
dirPath = join(base, key)
if (!existsSync(dirPath)) {
mkdirSync(dirPath)
}
}
resolvePath(paths[key] as Record, dirPath)
} else if (t === "string") {
paths[key] = join(base, paths[key] as string)
}
}
}
resolvePath(paths)
< /code>
Я думаю, вы видели, что «любое», которое я хотел представлять подстановочный знак < /p>
// I want paths like "./content/pages/Category#1/Article#2/files"
// ~~~~~~~~~~~~~~~~~~~~ = "any"
pages: {
self,
any: {
self,
attachments: { self },
files: { self },
},
},
< /code>
Это проблема, представляющая, что «любое» в этом решении сложно. Структура статического пути проста, но она становится сложной при сопоставлении паттернов. Сложность отображается, особенно при написании функции Concat с красивым типом.type Dir = `${Name}/${"" | Content}`
// prettier-ignore
export type Paths = Dir
Опция № 2: Такой беспорядок, он вовсе не работает
не , пытайтесь понять, не можете ли вы, просто возьмите все эти meta-programming для развлечения
import { join } from "node:path"
// "ts-arithmetic" package is really cool, arithmetic with number types!
import type { Add, Lt, Subtract } from "ts-arithmetic"
type File = string
interface Dir {
name: string
children: Item[]
}
type Item = Dir | File
function dir(name: T, ...children: U) {
return {
name,
children,
} as const
}
const wildCard: string = "*"
const pathss = dir(
"",
dir("b", dir("haha", dir("wildCard", dir("attachments", dir("files")), dir("files")))),
dir("content", dir("pages", dir(wildCard, dir("attachments"), dir("files")))),
dir("a", dir("pagesaa", dir(wildCard, dir("attachments"), dir("files")))),
)
type Paths = typeof pathss
type Children = T["children"][number]
type GetName = T extends Dir ? T["name"] : T
type GetDir = T extends Dir ? T : never
type SubPaths = GetName
type SubDirs = GetDir
type Indices = {
[K in keyof T]: K
}[number]
type IndexOf = {
[K in Indices]: GetName extends T ? K : never
}[Indices]
type Range =
Lt extends 1 ? A | Range : never
type a = Indices
type t = Range
type s = IndexOf
type Slices = Length extends 0
? []
: [SubDirs["name"], ...Slices]
// I gotta try another way...
const test: Slices = ["b", "pages", "asdfasdfasdfasdf"]
type As = T extends U ? T : never
type Slices2 = {
length: Length
} & {
[K in Range]: K extends 0
? SubDirs["name"]
: Slices2[As]
}
// Why is this not erroring?!
const test2: Slices = ["content", "haha", "b"]
function joinHelper<
U extends [...string[]] & Slices2,
Length extends number = U["length"],
Base extends Dir = Paths,
>(base: Base, [slice, ...slices]: [...U]): string {
return join(slice, joinHelper(base, slices))
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -structure
Решение TypeScript для управления структурой пути файловой системы [закрыто] ⇐ Javascript
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как получить, изменить размер и сохранить изображение на пути файловой системы.
Anonymous » » в форуме C# - 0 Ответы
- 10 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как получить, изменить размер и сохранить изображение на пути файловой системы.
Anonymous » » в форуме C# - 0 Ответы
- 7 Просмотры
-
Последнее сообщение Anonymous
-