我试图用对象析构来缩小受歧视类型的范围,但没有成功.我以为打字本能从v4.4年前就推断出来.
但是,此代码中的I cannot do it(仅为IDEA的一个示例):
type WritableRecord = {
someField: 'a'
}
type ReadonlyRecord = {
otherField: 'b'
}
type Writable = {
readonly: false;
} & WritableRecord;
type Readonly = {
readonly: true;
} & ReadonlyRecord;
export type RecordProps = Readonly | Writable
type Fn = (props: RecordProps) => void
const fn: Fn = ({ readonly, ...props }) => {
switch (readonly) {
case true:
const readonlyCheck: ReadonlyRecord = props
break;
case false:
const writableCheck: WritableRecord = props
break
}
}
但在不 destruct it works的情况下:
type WritableRecord = {
someField: 'a'
}
type ReadonlyRecord = {
otherField: 'b'
}
type Writable = {
readonly: false;
} & WritableRecord;
type Readonly = {
readonly: true;
} & ReadonlyRecord;
export type RecordProps = Readonly | Writable
type Fn = (props: RecordProps) => void
const fn: Fn = (props) => {
switch (props.readonly) {
case true:
{
const { readonly, ...readonlyProps } = props
const readonlyCheck: ReadonlyRecord = readonlyProps
break;
}
case false:
{
const { readonly, ...writableProps } = props
const writableCheck: WritableRecord = writableProps
break;
}
}
}
也许,我的V4.4声明是错误的,还是有错误?