我希望创建一个带有判别值的联合类型,但不需要传递判别值。
以下是我的当前代码:
interface Single<T> {
multiple?: false // this is optional, because it should be the default
value: T
onValueChange: (value: T) => void
}
interface Multi<T> {
multiple: true
value: T[]
onValueChange: (value: T[]) => void
}
type Union<T> = Single<T> | Multi<T>
我使用以下内容进行测试:
function typeIt<T>(data: Union<T>): Union<T> {
return data;
}
const a = typeIt({ // should be Single<string>
value: "foo",
onValueChange: (value) => undefined // why value is of type any?
})
const b = typeIt({ // should be Single<string>
multiple: false,
value: "foo",
onValueChange: (value) => undefined
})
const c = typeIt({ // should be Multi<string>
multiple: true,
value: ["foo"],
onValueChange: (value) => undefined
})
但是我收到了一堆错误和警告...
在
const a
的onValueChange
中,参数value
的类型是any
。当显式设置multiple: false
(例如在const b
中)时,它会被正确地推断为string
。const c
根本不起作用。我得到了这个错误:"Type 'string' is not assignable to type 'string[]'"。
您有任何解决方法吗?
我用这段代码创建了一个TypeScript Playground。