有没有办法将联合类型转换为交集类型:
type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void
Run Code Online (Sandbox Code Playgroud)
我想应用转换FunctionUnion来获取FunctionIntersection
如何缩小/分裂/分解一种可能受歧视的联合类型?
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) 我有一个与此类似的对象类型:
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)