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

2024 年 Interface OR Type 如何选择?

  •  
  •   tlerbao · 67 天前 · 1407 次点击
    这是一个创建于 67 天前的主题,其中的信息可能已经有所发展或是发生改变。

    前端菜一枚 关于 typescript Interface OR Type 如何选择?

    Google 搜索第一条

    https://www.totaltypescript.com/type-vs-interface-which-should-you-use

    英文菜,大致结论是 默认建议全部使用 type ,只在需要(继承)的时候使用 interface 。

    type 虽然可以 & ,但笔者说效率弱于 extends 。

    不知道大家 interface 和 type 是怎么选择的?

    8 条回复    2024-02-21 10:09:07 +08:00
    sch1111878
        1
    sch1111878  
       67 天前
    如果只是定义数据对象声明, 就 type

    我原来是用 interface 的, 但是看 ant-design-pro(umi) 的项目都是用的 type, 我现在也改用 type 了

    也刻意去搜过, 包括官方的问题, 并没有看出特别明显的内容, 随主流就好
    huijiewei
        2
    huijiewei  
       67 天前
    type 和 interface 不精通很难确定用哪个。所以我全用 type 了。
    Leviathann
        3
    Leviathann  
       67 天前
    听说 interface 是 lazy 的,大代码库里性能会更好
    SayHelloHi
        4
    SayHelloHi  
       67 天前
    有时候 type 一把梭 有时候 interface 一把梭
    songray
        5
    songray  
       67 天前
    简单类型/业务类型 => interface
    类型体操 => type
    extends > &
    caisanli
        6
    caisanli  
       67 天前
    type 一把梭,少写几个字母(/doge
    Amyang
        7
    Amyang  
       67 天前
    这文章里说的“But the TS team recommends you default to using interface and only use type when you need to.”
    tlerbao
        8
    tlerbao  
    OP
       66 天前
    @Amyang 但是他又说:I'd like to recommend the opposite. The features of declaration merging and implicit index signatures are surprising enough that they should scare you off using interfaces by default.

    并且这两天我搜索的结果看,还是推荐 type 的多,包括 ant design pro 团队
    https://pro.ant.design/zh-CN/docs/type-script

    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   888 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:50 · PVG 05:50 · LAX 14:50 · JFK 17:50
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.