theme: hydrogen
情景: 有个Card组件 需要接受2d或者3d的参数 但是不知道里面的属性是有没有定义的
?可不可以 (失败)
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
}
}
不理想做法(可以)
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官网:https://www.typescriptlang.org/
https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
在 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;
}
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
}
}