背景
如果你报的错误和我一样,或者对错误发生的原因感兴趣,可以接着往下看。
我的需求是希望继承 CSSTransitionProps
来实现自定义组件的属性,可是他报了错。
An interface can only extend an object type or intersection of object types with statically known members.
搜了一个较为满意的答复
A class can implement an interface or type alias, both in the same exact way. Note however that a class and interface are considered static blueprints. Therefore, they can not implement / extend a type alias that names a union type.
翻译过来的意思就是类和接口不能 implement / extends 联合类型的类型别名。
就像你用 interface 去 extends 一个 class 或另一个 interface 是可以的,但是你不能去 extends 联合类型。
思路
看到 一篇文章 比较了 interface 和 type 的用法:
interface Foo {
a: string;
}
interface Bar extends Foo {
b: number;
}
type 可以用 & 实现类似的效果(我把 Foo 的定义方式也改成了 type)
type Foo = {
a: string;
}
type Bar = Foo & {
b: number;
}
回到原来的问题,既然 interface 走不通,为何不试试 type ?
于是我将
interface TransitionProps extends CSSTransitionProps{}
改写成了
type TransitionProps = CSSTransitionProps & {}
错误完美解决~~~