V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
yazoox
V2EX  ›  TypeScript

ts 在 interface 定义时添加了泛型,使用该 interface 时候,能够不添加模板参数 或者 使用默认的 参数么?

  •  
  •   yazoox · 2022-05-30 11:22:41 +08:00 · 1246 次点击
    这是一个创建于 668 天前的主题,其中的信息可能已经有所发展或是发生改变。
    interface item<T> {
        id: string;
        text: string;
        data?: T
    }
    
    const a: item<number> = {
        id: "1",
        text: "test1"
    };
    
    console.log(a);
    

    如上所示。其实 a 里面压根就没有使用 data ,但我使用 item 的时候,必须给模板参数 T 指定一个。 这个是必须的么?

    不如直接使用 any 好了?

    interface item {
        id: string;
        text: string;
        data?: any
    }
    
    
    3 条回复    2022-05-30 12:20:16 +08:00
    Leviathann
        1
    Leviathann  
       2022-05-30 11:24:14 +08:00
    never
    mufeng
        2
    mufeng  
       2022-05-30 11:38:14 +08:00
    interface item<T = unknown>
    GentleFifth
        3
    GentleFifth  
       2022-05-30 12:20:16 +08:00 via Android
    泛型可以有默认类型
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4572 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 10:06 · PVG 18:06 · LAX 03:06 · JFK 06:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.