TypeScript:オプションのマージタイプ

Sep 12 2020

タイプaとタイプがbありますが、これは任意の数のタイプで機能するはずです。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

オプションでこれらすべてのタイプをマージするタイプを作成したいので、secondフィールドがある場合は、thirdフィールドもあるはずですが、両方を持っている必要はありません。

良い:

const aa = {
     first: 1,
     second: "hi",
     third: "hello"
}

const ab = {
     first: 1
}

const ac = {
     second: "hi",
     third: "hello"
}

悪い:

const bb = {
     first: 1,
     second: "hi"
}

どうすればそのようなタイプを定義できますか?

回答

6 Lesiak Sep 12 2020 at 05:15
type None<T> = {[K in keyof T]?: never}
type EitherOrBoth<T1, T2> = T1 & None<T2> | T2 & None<T1> | T1 & T2

type abcombined = EitherOrBoth<a,b>

より詳細な例を参照してください:Typescriptインターフェイスはプロパティの共起制約を表現できますか

遊び場リンク

KaranKumar Sep 12 2020 at 05:01

あなたがそれをすることができるかどうかはわかりません。これは私がすることです:

「|」を使用できます 変数を定義する際の演算子。

type a = {
    first: number
}

type b = {
    second: string
    third: string
}

const test: a | b ={ first: 3, second: 'string'}