有没有办法将联合类型转换为交集类型:
type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void
Run Code Online (Sandbox Code Playgroud)
我想应用转换FunctionUnion来获取FunctionIntersection
我收到以下错误:
type Union = { type: "1"; foo: string } | { type: "2"; bar: number };
function doSomething = (object: Union) => {
const { foo } = object
// ^ TS2339: Property 'foo' does not exist on type 'Union'.
console.log(object.bar)
// ^ TS2339: Property 'bar' does not exist on type 'Union'.
}
Run Code Online (Sandbox Code Playgroud)
期望的结果:
typeof foo === string | undefined
typeof bar === number | undefined
Run Code Online (Sandbox Code Playgroud)
如何在没有显式类型保护的情况下访问属性,例如:
const foo = o.type === 1 ? o.foo : undefined
const bar …Run Code Online (Sandbox Code Playgroud)