You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过泛型动态传递TypeScript接口至方法?编译报错求解

问题解决:TypeScript泛型接口传递编译错误

错误原因

你定义的泛型<I>没有任何类型约束,TypeScript无法确定传入的类型一定包含data属性,因此抛出Property 'data' does not exist on type 'I'的编译错误。

解决步骤

1. 定义基础约束接口

在/types.ts中创建一个基础接口,统一所有页面数据类型的公共结构,避免重复代码并提供泛型约束依据:

// /types.ts
export interface IBasePage {
  data: {
    id: number;
    user_created: string;
    date_created: Date;
    user_updated: string;
    title: string;
    content: string;
  }
}

// 让现有接口继承基础接口
export interface IPage extends IBasePage {}

export interface IAnotherPage extends IBasePage {
  data: {
    // 扩展基础接口的data字段,添加专属属性
    ...IBasePage['data'];
    image: string;
  }
}

2. 给泛型函数添加约束

修改/utils/makeTitle.ts中的函数,通过extends关键字限制泛型必须符合IBasePage的结构,让TypeScript确认传入类型包含data及title属性:

// /utils/makeTitle.ts
//@ts-check
import { IBasePage } from '@/types';

export async function makeTitle<I extends IBasePage>(pageData: I) {
    const title: string = pageData.data.title;
    return title;
}

3. 调用泛型函数(可选优化)

调用时TypeScript会自动推断泛型类型,无需显式指定,代码更简洁:

// /app/page.tsx
//@ts-check
import { IPage } from '@/types';
import { makeTitle } from '@/utils/makeTitle';

export default async function Page({ pageId }: { pageId: number }) {
    const pageData: IPage = await getCollectionData('mypage', '?fields=*.*');
    // 自动推断泛型为IPage,也可显式写makeTitle<IPage>(pageData)
    const metadatas = await makeTitle(pageData);
}

/app/another/page.tsx同理:

// /app/another/page.tsx
//@ts-check
import { IAnotherPage } from '@/types';
import { makeTitle } from '@/utils/makeTitle';

export default async function AnotherPage({ pageId }: { pageId: number }) {
    const pageData: IAnotherPage = await getCollectionData('another_page', '?fields=*.*');
    const metadatas = await makeTitle(pageData);
}

核心逻辑

通过泛型约束<I extends IBasePage>,强制传入的类型必须符合基础接口结构,既保证了类型安全,又实现了不同接口的动态传递需求。

内容的提问来源于stack exchange,提问作者Jee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 20:42:50