hahaFck

typescript 如何忽略泛型参数啊?

  •  
  •   hahaFck · Jun 25, 2024 · 2374 views
    This topic created in 692 days ago, the information mentioned may be changed or developed.
    比如我定义了一个类型带有泛型参数<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 replies    2024-06-26 13:56:01 +08:00
    Opportunity
        1
    Opportunity  
       Jun 25, 2024
    给工具方法再加个类型参数,然后继续写 T 呗
    xiaoming1992
        2
    xiaoming1992  
       Jun 25, 2024
    添加一个默认参数,如 BaseDataType

    ```typescript

    export interface ReportTreeNode<T extends BaseDataType = BaseDataType> {

    }

    ```
    xiaoming1992
        3
    xiaoming1992  
       Jun 25, 2024
    或者用 any ,再忽略 eslint 提示
    hahaFck
        4
    hahaFck  
    OP
       Jun 25, 2024
    @xiaoming1992 #2 嗯,ts 好像只能在有默认参数的时候才能忽略掉泛型
    hahaFck
        5
    hahaFck  
    OP
       Jun 25, 2024
    @Opportunity 写多了,感觉好麻烦,关键有的时候方法就不关心泛型呢
    yanyiming
        6
    yanyiming  
       Jun 26, 2024
    那就把默认参数设为 any.
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3766 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 32ms · UTC 04:16 · PVG 12:16 · LAX 21:16 · JFK 00:16
    ♥ Do have faith in what you're doing.