gpt4 book ai didi

reactjs - typescript react : Union type for props does not display error when providing excess properties

转载 作者:搜寻专家 更新时间:2023-10-30 21:27:08 24 4
gpt4 key购买 nike

我正在尝试为 React 组件的 props 使用联合类型

type Props =
| {
type: "string"
value: string
}
| {
type: "number"
value: number
}
| {
type: "none"
}

class DynamicProps extends React.Component<Props> {
render() {
return null
}
}

// Ok
const string_jsx = <DynamicProps type="string" value="hello" />

// Error as expected, value should be a string
const string_jsx_bad = <DynamicProps type="string" value={5} />

// Ok
const number_jsx = <DynamicProps type="number" value={5} />

// Error as expcted value should be a number
const number_jsx_bad = <DynamicProps type="number" value="hello" />

// Error as expected, invalid isn't a property on any of the unioned types
const extra = <DynamicProps type="string" value="extra" invalid="what" />

// No error? There should be no value when type="none"
const none_jsx = <DynamicProps type="none" value="This should be an error?" />

// Ok, seems like value has become optional
const none2_jsx = <DynamicProps type="none" />

// Error as expected, value is not present. Value doesn't seem to be made optional all the time
const required = <DynamicProps type="string" />

它似乎部分起作用,因为根据 type Prop 有效的 Prop 会改变。然而,虽然没有出现在联合中任何类型上的额外属性将是一个错误,但似乎出现在至少一个联合类型中但不属于基于判别属性的类型将不是一个错误错误。

我不确定为什么会这样。使用联合类型作为 React 组件的 props 是一种反模式吗?

最佳答案

问题与涉及工会时过多的属性(property)检查有关。你可以阅读这个答案 here到一个类似的问题。它的要点是联合的额外属性检查允许任何成员的任何键出现在对象上。我们可以通过引入 never 类型的额外成员来解决这个问题,以确保具有过多属性的对象不会错误地与特定成员兼容:

type Props =
| {
type: "string"
value: string
}
| {
type: "number"
value: number
}
| {
type: "none"
}

type UnionKeys<T> = T extends any ? keyof T : never;
type StrictUnionHelper<T, TAll> = T extends any ? T & Partial<Record<Exclude<UnionKeys<TAll>, keyof T>, never>> : never;
type StrictUnion<T> = StrictUnionHelper<T, T>

class DynamicProps extends React.Component<StrictUnion<Props>> {
render() {
return null
}
}
// error now
const none_jsx = <DynamicProps type="none" value="This should be an error?" />

关于reactjs - typescript react : Union type for props does not display error when providing excess properties,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52771362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com