ts 的类型可以做继承吗?

type type_a = {
    id:number
    OnThink?: (info: type_a)=>number
}
type type_b = type_a & {
    width:number
    OnThink?: (info: type_b)=>number
}
type type_c = type_a & {
    delay:number
    OnThink?: (info: type_c)=>number
}

function async_d<T extends type_a = type_a>(info:T){
    let count = info.OnThink?.(info)
    // ...
}

// 使用时
let newInfo:type_b = {
    id:2,
    OnThink:info=>{ return info.id + info.width }
}
async_d(newInfo)

希望

  1. asyn_c函数接受所有的type_a的变型或者拓展类型。
  2. 该拓展类型中的成员函数OnThink含有形参的类型为拓展类型。
    是否能在type_a中做好对Onthink的类型定义,而不是在定义type_btype_c的时候重新定义?
阅读 5.8k
2 个回答

来看 TypeScript Playground

interface type_a  {
    id: number
}
interface type_b extends type_a {
    width: number
}
interface type_c extends type_a {
    delay: number
}

type OnThink<T> = {
    OnThink?: (info: T) => number;
}

type Merge<T> = T & OnThink<T>;

function async_d<T extends type_a = type_a>(info: Merge<T>) {
    let count = info.OnThink?.(info)
    // ...
}

// 使用时
let newInfo: Merge<type_b> = {
    id: 2,
    width: 100,
    OnThink: info => { return info.id + info.width }
}
async_d(newInfo)

已参与了 SegmentFault 思否社区 10 周年「问答」打卡 ,欢迎正在阅读的你也加入。
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进