typescript互斥类型判断

37 阅读1分钟

情景: 有个Card组件 需要接受2d或者3d的参数 但是不知道里面的属性是有没有定义的

image.png

?可不可以 (失败)

interface I2dcard {
    x: number
    y: number
}
interface I3dcard {
    x: number
    y: number
    z: number
    isThreedcard: true
}

type CardProps = I2dcard | I3dcard


function Card(props: CardProps) {
   
    if (props?.isThreedcard) {
        //TO DO
    }
    return {
        //Jsx
    }
}

image.png

不理想做法(可以)

interface I2dcard {
    x: number
    y: number
}
interface I3dcard {
    x: number
    y: number
    z: number
    isThreedcard: true
}

type CardProps = I2dcard | I3dcard


function Card(props: CardProps) {
    const { x, y, z } = props
    if (z) {
        //TO DO
    }
    return {
        //Jsx
    }
}

要是3d里面多了很多其他属性一个个判断太麻烦了

官网给出答案

ts官网:www.typescriptlang.org/

www.typescriptlang.org/docs/handbo…

在 Using type predicates 那一块

案例:

type Fish = { swim: () => void };
type Bird = { fly: () => void };
declare function getSmallPet(): Fish | Bird;
// ---cut---
function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

image.png

resolve

interface I2dcard {
    x: number
    y: number
}
interface I3dcard {
    x: number
    y: number
    z: number
    isThreedcard: true
}

type CardProps = I2dcard | I3dcard

function isThreedCard(card: CardProps): card is I3dcard {
    return (card as I3dcard).z !== undefined;
}
function Card(props: CardProps) {
    const is3dCard = isThreedCard(props)
    if (is3dCard) {
        const { z } = props
    } else {
        const { x, y } = props
    }
    return {
      //Jsx
    }
}

代码demo测试

demo