英文:
TypeScript define new type based on existing type
问题
以下是翻译好的部分:
我对ts不熟悉。
有两种现有类型:
type A {
prop1: string
prop2: B
}
type B {
prop3: string
prop4: boolean
}
现在我想创建一个新类型,将A和B合并为一个扁平版本
{
prop1: string
prop3: string
prop4: boolean
}
如何在typescript中实现?通过引用现有类型。
英文:
I am new to ts.
there are two exising type:
type A {
prop1: string
prop2: B
}
type B {
prop3: string
prop4: boolean
}
now I want to create a new type as flatted version of A+B
{
prop1: string
prop3: string
prop4: boolean
}
how to do this in typescript? by referencing existing types.
答案1
得分: 2
type A = {
prop1: string
prop2: B
}
type B = {
prop3: string
prop4: boolean
}
type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type Flatten<T, K extends keyof T> = UnionToIntersection<T[K]> & Omit<T, K>;
type Both = Flatten<A,'prop2'>
const result: Both = {prop1: 'one', prop3: 'two', prop4: false}
Edit: this is simpler:
type Flatten<T, K extends keyof T> = Omit<T, K> & T[K];
type Both = Flatten<A,'prop2'>
英文:
You can use this type:
type A = {
prop1: string
prop2: B
}
type B = {
prop3: string
prop4: boolean
}
type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends ((k: infer I) => void) ? I : never;
type Flatten<T, K extends keyof T> = UnionToIntersection<T[K]> & Omit<T, K>;
type Both = Flatten<A,'prop2'>
const result: Both = {prop1: 'one', prop3: 'two', prop4: false}
Edit: this is simpler:
type Flatten<T, K extends keyof T> = Omit<T, K> & T[K];
type Both = Flatten<A,'prop2'>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论