取一个简单的反应元件
interface MyProps {
color: string
name?: string
height?: number
isBoy?: boolean
// only add the following if isBoy is true
actionHero: string
nickname: string
}
function MyComponent(props: MyProps){
...
}正如您所看到的,目标是如果将actionHero和nickName设置为true,则isBoy和isBoy是必需的。否则,它们就不会被使用。
我假设这是通过类型记录中的函数重载来完成的,但是你是如何在反应中做到的呢?
发布于 2021-10-11 14:55:55
在这种情况下,您不需要使组件超载。COnsider这个例子:
import React from 'react'
type Boy = {
color: string
name?: string
height?: number
isBoy: false
}
type ExtendedBoy = Omit<Boy, 'isBoy'> & {
actionHero: string
nickname: string
isBoy: true;
}
type Props = Boy | ExtendedBoy;
function MyComponent(props: Props) {
if (props.isBoy) {
props.nickname // stirng
} else {
props.isBoy // false
}
return <div></div>
}
const withBoy = <MyComponent isBoy color="red" actionHero={'batman'} nickname={'qwert'} /> // ok
const withoutBoy = <MyComponent isBoy={false} color="red" /> // ok我用歧视工会代替了功能过载。
但是,如果您仍然想要重载组件,就没有人能阻止您:
import React, { FC } from 'react'
type Boy = {
color: string
name?: string
height?: number
isBoy: false
}
type ExtendedBoy = Omit<Boy, 'isBoy'> & {
actionHero: string
nickname: string
isBoy: true;
}
const MyComponent: FC<Boy> & FC<ExtendedBoy> = (props) => {
if (props.isBoy) {
props.nickname // stirng
} else {
props.isBoy // false
}
return <div></div>
}
const withBoy = <MyComponent isBoy color="red" actionHero={'batman'} nickname={'qwert'} /> // ok
const withoutBoy = <MyComponent isBoy={false} color="red" /> // ok请注意,函数的交集会产生函数重载FC<Boy> & FC<ExtendedBoy>。
发布于 2021-10-11 14:58:30
这是可能的,因为类型没有条件逻辑,不能相互依赖,而是使用两个映射类型。一个用于可选属性,另一个用于所需属性。
interface MyProps {
color: string
name?: string
height?: number
isBoy?: false | null
}
interface MyProperRequired extends MyProps {
isBoy: true
// only add the following if isBoy is true
actionHero: string
nickname: string
}
function MyComponent(props: MyProps | MyProperRequired) {
}
MyComponent({ color: "red", height: 1, name: "hi", isBoy: true })https://stackoverflow.com/questions/69528140
复制相似问题