MST

星途 面试题库

面试题:Next.js中如何对动态路由参数进行基础类型检查

在Next.js项目里,假设你有一个动态路由页面`pages/post/[id].js`,其中`id`参数应该是数字类型。请描述你会使用哪些方法对`id`进行类型检查,并且简单举例代码实现。
21.9万 热度难度
前端开发Next.js

知识考点

AI 面试

面试题答案

一键面试
  1. 使用JavaScript的typeofNumber.isNaN方法
    • getStaticPropsgetServerSideProps函数中获取id后进行检查。
    • 示例代码如下:
export async function getStaticProps(context) {
    const id = context.params.id;
    if (typeof id ==='string' &&!Number.isNaN(parseInt(id))) {
        const numId = parseInt(id);
        // 这里可以继续使用numId进行数据库查询等操作
        return {
            props: {
                numId
            },
            revalidate: 60
        };
    } else {
        return {
            notFound: true
        };
    }
}
  1. 使用zod库进行类型验证
    • 先安装zod库:npm install zod
    • 示例代码如下:
import { z } from 'zod';

const idSchema = z.string().transform(Number).refine(Number.isFinite, {
    message: 'Invalid number'
});

export async function getStaticProps(context) {
    const id = context.params.id;
    const validationResult = idSchema.safeParse(id);
    if (validationResult.success) {
        const numId = validationResult.data;
        // 这里可以继续使用numId进行数据库查询等操作
        return {
            props: {
                numId
            },
            revalidate: 60
        };
    } else {
        return {
            notFound: true
        };
    }
}
  1. 使用io - ts库进行类型验证
    • 先安装io - ts库:npm install io - ts
    • 示例代码如下:
import { type, number } from 'io - ts';

const IdType = type({
    id: number
});

export async function getStaticProps(context) {
    const id = context.params.id;
    const result = IdType.decode({ id: parseInt(id) });
    if (result.isRight()) {
        const numId = result.right.id;
        // 这里可以继续使用numId进行数据库查询等操作
        return {
            props: {
                numId
            },
            revalidate: 60
        };
    } else {
        return {
            notFound: true
        };
    }
}