一个错误引发的对 interface 和 type 的思考(未完)

背景

如果你报的错误和我一样,或者对错误发生的原因感兴趣,可以接着往下看。
在这里插入图片描述

我的需求是希望继承 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 & {}
错误完美解决~~~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值