首页 > 解决方案 > 有没有办法创建一个项目的类型取决于第二个的界面?

问题描述

例如,如果我有这个对象:

{a, b}

我想确保如果a是'a',b应该是一个数字,如果a是'b',b应该是一个字符串,如果a是'c',b应该是一个日期。
如果我将界面拆分为三个选项:

interface {
    a: 'a'
    b: number
}

interface {
    a: 'b'
    b: string
}

interface {
    a: 'c'
    b: Date
}

标签: typescript

解决方案


你很接近:

interface A {
  a: 'a'
  b: number
}

interface B {
  a: 'b'
  b: string
}

interface C {
  a: 'c'
  b: Date
}

type Union = A | B | C

推荐阅读