【问题标题】:Conditional interface in TypeScriptTypeScript 中的条件接口
【发布时间】:2020-03-12 13:44:34
【问题描述】:

我有以下情况:两个不同的接口(A,B)和一个函数,它将参数props 作为条件接口/联合类型。但是如果没有在两个接口中声明它,我就不能使用 prop。

Example:

interface A {
    name: string
};

interface B {
    age: number
};

function foo(props: A | B) {
    return props.name;
}

【问题讨论】:

    标签: javascript typescript interface


    【解决方案1】:

    这是正确的 - 您不知道 name 键是否存在于您的 props 对象上。

    你有两个选择:

    1

    function foo(props: A | B): string | undefined {
      if ('name' in props) {
        return props.name
      }
    }
    

    2.

    interface A {
      name: string
      age?: undefined
    }
    
    interface B {
      name?: undefined
      age: number
    }
    
    function foo(props: A | B): string | undefined {
      return props.name
    }
    

    为什么?

    Typescript 正确地警告您,因为没有 name 键的对象与未定义 name 键的对象不同。想象一下:

    const a = {
      // name is missing
      age: 1
    }
    
    const b = {
      name: 'test',
      age: undefined
    }
    
    Object.keys(a) == ['age']
    Object.keys(b) == ['name', 'age']
    
    if ('age' in b) {
      console.log('this is true')
    }
    
    if ('name' in a) {
      throw new Error(`This is false`)
    }
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      function foo(props: A | B) {
          if ((props as A).name) {
              return (props as A).name;
          }
          return undefined;
      }
      

      【讨论】:

        猜你喜欢
        • 2017-10-27
        • 2018-09-06
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多