有没有办法将联合类型转换为交集类型:
type FunctionUnion = () => void | (p: string) => void
type FunctionIntersection = () => void & (p: string) => void
Run Code Online (Sandbox Code Playgroud)
我想应用转换FunctionUnion来获取FunctionIntersection
我有一个未知类型的联盟。我想得到它的合并类型。例如:
const a = {
x: 10
}
const b = {
y: 'qwer'
}
const array = [a, b]
type TArr = typeof array
// I use a function which receives an array as argument so I only have type of array from now on
type TUnion = keyof TArr[number] // { x: number } | { y: string }
type TMerge = ? // { x: number } & { y: string }
Run Code Online (Sandbox Code Playgroud)
哪里TMerge几乎相同
type TMerge …Run Code Online (Sandbox Code Playgroud) 我需要一种实用程序类型,可以将传递的联合中的两个或多个接口合并为一个,而不需要解决重复的 props 而是never覆盖。它应该像 Object.assign 一样工作,但适用于类型/接口。假设我们有三种类型:
type A = {a: number};
type B = {a: boolean, b: boolean};
type C = {c: boolean};
Run Code Online (Sandbox Code Playgroud)
我想要一些实用程序可以将它们合并为一个:
type MergedType = MergeTypes<A|B|C>;
Run Code Online (Sandbox Code Playgroud)
在结果中我想得到以下界面:
type MergedType = {
a: boolean, // overwriting, not `never` in case of using intersection (A & B & C)
b: boolean,
c: boolean
}
Run Code Online (Sandbox Code Playgroud)
有什么解决方案可以达到这种行为吗?我只能为具有单独泛型参数的两个接口编写实用程序
type MergeTypes<S, T> = Omit<S, keyof T> & T;
type MergedType = MergeTypes<A, B>;
Run Code Online (Sandbox Code Playgroud)
但我不知道如何参考前面的参数迭代联合以达到数组归约逻辑。先感谢您!
我有一个类型:
type first = {
one: number;
two: string;
three: {
four: string,
five: number,
}
}
Run Code Online (Sandbox Code Playgroud)
它适用于我在应用程序的一部分中声明的一个变量实例,但不完全适用于另一个(第二个)变量实例。
适合变量第二个实例的类型如下所示:
type second = {
one: number;
two: string;
three: {
four: string,
five: number[], //difference
}
}
Run Code Online (Sandbox Code Playgroud)
我不想为了微小的差异而从头开始声明一个新类型,并希望first通过替换 property 的类型来同化现有类型three。
我试图这样做:
type second = Pick<first, Exclude<keyof first, 'three'>> & {
three: {
four: string,
five: number[], //difference
}
}
Run Code Online (Sandbox Code Playgroud)
但它给了我一个错误,我在悬停时得到了这个类型定义:
type second = {
one: number;
two: string;
three: {
four: string,
five: number,
};
three: { …Run Code Online (Sandbox Code Playgroud)