[Typescript] Awaited Type

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-5.html

 

post.server.ts:

export type Post = {
  slug: string;
  title: string;
};

export async function getPosts(): Promise<Post[]> {
  const posts = [
    { slug: "frist-post", title: "My First Post" },
    { slug: "trail-riding-with-onewheel", title: "Trail Riding with Onewheel" },
  ];

  return posts;
}

 

posts/index.ts

import { json, LoaderFunction } from "@remix-run/node";
import { useLoaderData, Link } from "@remix-run/react";
import { getPosts } from "~/models/post.server";

type LoaderData = {
  posts: Awaited<ReturnType<typeof getPosts>>;
};

export const loader: LoaderFunction = async () => {
  const posts = await getPosts();
  return json<LoaderData>({ posts });
};

export default function PostsRouter() {
  const { posts } = useLoaderData() as LoaderData;

  return (
    <main>
      <h1>Posts</h1>
      <ul>
        {posts.map((post) => (
          <li key={post.slug}>
            <Link to={post.slug} className="text-blue-600 underline">
              {post.title}
            </Link>
          </li>
        ))}
      </ul>
    </main>
  );
}

 

posted @ 2022-06-23 14:32  Zhentiw  阅读(256)  评论(0编辑  收藏  举报