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

typescript 如何忽略泛型参数啊?

  •  
  •   hahaFck · 3 天前 · 225 次点击
    比如我定义了一个类型带有泛型参数<T>

    ```typescript
    export interface ReportTreeNode<T extends BaseDataType> {
    data: T
    children: ReportTreeNode<T>[]
    relationshipWithParent: RelationshipWithParent
    nodeType: NodeType
    cellInfo?: CellInfo
    }
    ```

    但是我在写一些其他工具方法时,是不关心具体类型 T 的,在 java 中这个种情况可以写问号`?`代替,但是 typescript 不行,如果我写 any 的话,eslint 又提示我应该用 never ,我改成 never 后,调用这个方法时又报`<never>不能赋值给<T>`
    6 条回复    2024-06-26 13:56:01 +08:00
    Opportunity
        1
    Opportunity  
       3 天前
    给工具方法再加个类型参数,然后继续写 T 呗
    xiaoming1992
        2
    xiaoming1992  
       3 天前
    添加一个默认参数,如 BaseDataType

    ```typescript

    export interface ReportTreeNode<T extends BaseDataType = BaseDataType> {

    }

    ```
    xiaoming1992
        3
    xiaoming1992  
       3 天前
    或者用 any ,再忽略 eslint 提示
    hahaFck
        4
    hahaFck  
    OP
       3 天前
    @xiaoming1992 #2 嗯,ts 好像只能在有默认参数的时候才能忽略掉泛型
    hahaFck
        5
    hahaFck  
    OP
       3 天前
    @Opportunity 写多了,感觉好麻烦,关键有的时候方法就不关心泛型呢
    yanyiming
        6
    yanyiming  
       2 天前
    那就把默认参数设为 any.
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2144 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 01:01 · PVG 09:01 · LAX 18:01 · JFK 21:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.