【问题标题】:Extending 'generic' TypeScript interface扩展“通用”TypeScript 接口
【发布时间】:2020-04-09 17:10:39
【问题描述】:

考虑以下 TS 定义:

type GenericPropsWithChildren<T> = T & { children?: ReactNode };

type 没有问题,但我想知道是否有 interface 等价物?显然,可以将泛型 传递到 接口中,尽管这不是我所追求的,例如。 g.:

interface GenericPropsWithChildren<T> {
 children?: ReactNode;
 myProps: T; // not desired
}

这里的示例是在 React 代码的上下文中,但根本问题是基本的 TS。

【问题讨论】:

    标签: typescript typescript-generics


    【解决方案1】:

    在声明时必须知道接口的成员,在扩展中使用泛型类型参数违反了此规则。所以没有办法创建一个等效的通用接口。

    如果您已经知道类型参数,您实际上可以在接口中继承类型别名。只要所有成员在声明时都是已知的,就可以:

    import { ReactNode } from 'react'
    
    type GenericPropsWithChildren<T> = T & { children?: ReactNode };
    
    interface Concrete extends GenericPropsWithChildren<{ p: string }> {
    
    }
    

    Playground Link

    【讨论】:

    • 干杯,我怀疑会是这种情况,应该列在typeinterface之间的主要区别列表中。
    猜你喜欢
    • 2020-06-09
    • 1970-01-01
    • 2018-07-26
    • 2019-06-08
    • 2020-10-30
    • 2016-07-06
    • 2017-10-21
    • 2018-06-20
    • 2018-04-09
    相关资源
    最近更新 更多