[Typescript] Using tiny-invariant for narrowing type
2022/3/26 6:25:25
本文主要是介绍[Typescript] Using tiny-invariant for narrowing type,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import { json } from "remix"; import path from "path"; import fs from "fs/promises"; import parseFrontMatter from "front-matter"; import invariant from "tiny-invariant"; import { marked } from "marked"; export type Post = { slug: string; title: string; html: string; }; export type PostMarkdownAttributes = { title: string; }; type NewPost = { title: string; slug: string; markdown: string; }; function isValidPostAttributes( attributes: any ): attributes is PostMarkdownAttributes { return attributes?.title; } const postsPath = path.join(__dirname, "..", "posts"); export async function getPost(slug: string): Promise<Post> { const filepath = path.join(postsPath, slug + ".md"); const file = await fs.readFile(filepath); const { attributes, body } = parseFrontMatter(file.toString()); invariant( isValidPostAttributes(attributes), `Post ${filepath} is missing attributes` ); const html = marked(body); return { slug, html, title: attributes.title }; }
export const action: ActionFunction = async ({ request }) => { const formData = await request.formData(); await new Promise((res) => setTimeout(res, 1000)); const title = formData.get("title"); const slug = formData.get("slug"); const markdown = formData.get("markdown"); const errors: PostError = {}; if (!title) errors.title = true; if (!slug) errors.slug = true; if (!markdown) errors.markdown = true; if (Object.keys(errors).length) { return json(errors); } invariant(typeof title === "string"); invariant(typeof slug === "string"); invariant(typeof markdown === "string"); await createPost({ title, slug, markdown }); return redirect("/admin"); };
这篇关于[Typescript] Using tiny-invariant for narrowing type的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-15在使用平台私钥进行解密时提示 "私钥解密失败" 错误信息是什么原因?-icode9专业技术文章分享
- 2024-11-15Layui框架有哪些方式引入?-icode9专业技术文章分享
- 2024-11-15Layui框架中有哪些减少对全局环境的污染方法?-icode9专业技术文章分享
- 2024-11-15laydate怎么关闭自动的日期格式校验功能?-icode9专业技术文章分享
- 2024-11-15laydate怎么取消初始日期校验?-icode9专业技术文章分享
- 2024-11-15SendGrid 的邮件发送时,怎么设置回复邮箱?-icode9专业技术文章分享
- 2024-11-15使用 SendGrid API 发送邮件后获取到唯一的请求 ID?-icode9专业技术文章分享
- 2024-11-15mailgun 发送邮件 tags标签最多有多少个?-icode9专业技术文章分享
- 2024-11-15mailgun 发送邮件 怎么批量发送给多个人?-icode9专业技术文章分享
- 2024-11-15如何搭建web开发环境并实现 web项目在浏览器中访问?-icode9专业技术文章分享