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

TypeScript导出多个类型别名时报「Unexpected token」错误求助

解决TypeScript导出多个类型别名的语法错误及复用方案

你的代码之所以报「Unexpected token」错误,核心是语法不符合TypeScript的类型导出规则——你不能把类型定义写在export type {}这个导出块里面,这个语法块只能用来导出已经定义好的类型,不能在里面声明新类型。

正确的导出写法有两种:

  1. 先定义类型,再批量导出
// 先单独定义所有需要的类型
type abc = { a: string; }; 
type bbc = { bbb: string };

// 用export type {}批量导出已定义的类型
export type { abc, bbc };
  1. 定义类型时直接导出
    如果不需要先在当前文件内部使用这些类型,也可以在定义时直接加上export:
export type abc = { a: string; }; 
export type bbc = { bbb: string };

关于类型复用的优化方案

要最大化复用类型,我推荐这样做:

  • 集中管理类型:把常用的类型都放在一个单独的文件里(比如src/types/index.ts),这样所有需要用到这些类型的文件都能统一导入,避免重复定义。
    // src/types/index.ts
    export type abc = { a: string; }; 
    export type bbc = { bbb: string };
    
    // 其他业务文件中导入使用
    import type { abc, bbc } from '../types';
    
  • 复用类型字段:如果多个类型有重复的字段,可以先定义一个基础类型,再通过交叉类型(&)来组合:
    // 基础通用类型
    type BaseEntity = { id: string; createTime: Date };
    
    // 基于基础类型扩展
    export type abc = BaseEntity & { a: string };
    export type bbc = BaseEntity & { bbb: string };
    

这样既保证了语法正确,又能高效复用你的类型啦~

内容的提问来源于stack exchange,提问作者ey dee ey em

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 12:07:48