TypeScript基于现有类型定义新类型

huangapple go评论66阅读模式
英文:

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&lt;U&gt; = (U extends any ? (k: U) =&gt; void : never) extends ((k: infer I) =&gt; void) ? I : never;
    type Flatten&lt;T, K extends keyof T&gt; = UnionToIntersection&lt;T[K]&gt; &amp; Omit&lt;T, K&gt;;
    
    type Both = Flatten&lt;A,&#39;prop2&#39;&gt;
    
    const result: Both = {prop1: &#39;one&#39;, prop3: &#39;two&#39;, prop4: false}

Edit: this is simpler:

type Flatten&lt;T, K extends keyof T&gt; =  Omit&lt;T, K&gt; &amp; T[K];
type Both = Flatten&lt;A,&#39;prop2&#39;&gt;

huangapple
  • 本文由 发表于 2023年4月13日 14:25:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定