ts接口声明中如何要求参数必须有呢?

    interface effectInfo {
        /** 起点 */
        source?: Vector
        /** 终点或目标方向 */
        destination?: Vector
        /** 施法者 */
        caster?: unit
        /** 目标者 */
        target?: unit

        /** 特效模型 */
        model: 自定义模型
        /** 特效句柄 */
        readonly _handle: effect
        /** 搜索半径 */
        width: number | undefined
    }

希望实现的类型判断是把castertarget看作一对,sourcedestination一对,当传参提供了其中一个时,也必然要提供另一个。

当提供了source时,那destination 也必须要有,反之亦然。


let a:effectInfo = { // 允许这样
  model:'aaa.mdl',
  width:20,
  caster:unit1,
  target:unit2
}

let b:effectInfo = { // 报异常,缺少target,缺少destination
  model:'aaa.mdl',
  width:20,
  source:unit1,
  target:unit2
} 

let c:effectInfo = { // 允许这样
  model:'aaa.mdl',
  width:20,
} 
阅读 1.6k
2 个回答
 interface effectInfo {
    model: 自定义模型
    readonly _handle: effect
    width: number | undefined
}

interface ct extends effectInfo{
    source: Vector
    destination: Vector
}
interface sd extends effectInfo{
    caster: unit
    target: unit
}

使用:
let a: sd | ct | effectInfo = {
    ...
}

一时也想不到怎么搞, 不过可以变通一下:

interface effectInfo {
  a?: {
    /** 起点 */
    source: Vector
    /** 终点或目标方向 */
    destination: Vector
  }
  b?: {
    /** 施法者 */
    caster: unit
    /** 目标者 */
    target: unit
  }

  /** 特效模型 */
  model: 自定义模型
  /** 特效句柄 */
  readonly _handle: effect
  /** 搜索半径 */
  width: number | undefined
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏