相关疑难解决方法(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
查看次数

如何缩小联合类型?

如何缩小/分裂/分解一种可能受歧视的联合类型?

kind: "bar"例如,在下面我想获取来自from的类型MyUnion

type MyUnion = { kind: "foo", foo: number } | { kind: "bar", bar: string };

// Here I want to somehow get the type { kind: "bar", bar: string } from MyUnion
type Narrowed = NarrowUnion<MyUnion, { kind: "bar" }>;
Run Code Online (Sandbox Code Playgroud)

typescript typescript-generics

8
推荐指数
1
解决办法
5451
查看次数

从对象类型创建常量数组类型

我有一个与此类似的对象类型:

type Fields = {
  countryCode: string;
  currency: string;
  otherFields: string;
};
Run Code Online (Sandbox Code Playgroud)

我还有一个与此类似的只读数组:

// Type: readonly ["countryCode", "currency", "otherFields"]
const allowedFields = ["countryCode", "currency", "otherFields"] as const;
Run Code Online (Sandbox Code Playgroud)

我希望能够根据Fields对象类型为此数组声明指定一个接口,以便对其进行任何更改也需要更改数组。像这样的东西:

// How to create 'SomeType'?
const allowedFields: SomeType = ["countryCode"] as const; // Should throw error because there are missing fields

const allowedFields: SomeType = ["extraField"] as const; // Should throw error because "extraField" is not in the object type 'Fields'
Run Code Online (Sandbox Code Playgroud)

typescript

3
推荐指数
1
解决办法
4471
查看次数

标签 统计

typescript ×3

typescript-generics ×1