相关疑难解决方法(0)

将联合类型转换为交集类型

有没有办法将联合类型转换为交集类型:

type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void
Run Code Online (Sandbox Code Playgroud)

我想应用转换FunctionUnion来获取FunctionIntersection

typescript

55
推荐指数
4
解决办法
4645
查看次数

解构/访问对象联合类型上可能存在或不存在的属性

我收到以下错误:

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)

destructuring typescript union-types object-destructuring

12
推荐指数
2
解决办法
5711
查看次数