自定义属性名称

时间:2019-11-04 16:48:12

标签: typescript typescript-typings

我想创建一个像这样的函数:

  render() {
    const  results  = this.props.data;
    if (results.lenght) { // I'm trying to check for storage length, but this does not work
      return (
        results.map((item, index) => {
          <div key={index}>
          <h1>
            {item.dstOffset}
          </h1>
          <h1>
            {item.rawOffset}
          </h1>
          <h1>
            {item.timeZoneId}
          </h1>
        </div>} )
      )
   }
   else {
     return (
       <div>loading</div>
     )
   }
  }
}

const mapStateToProps = state => ({ data: state.data });

并希望TypeScript理解这是有效的:

hello({ x: "hello", y: "world" })

但这不是:

const greeting = hello({ x: "hello", y: "world" })

greeting.x
greeting.y

我很确定可以在网络上的某个地方回答此问题,但是找不到合适的关键字来进行正确的研究,这就是我在这里的原因。

1 个答案:

答案 0 :(得分:2)

您可以使用泛型来做到这一点,告诉TypeScript它返回的内容与接收到的内容相同:

function hello<T>(obj: T): T {
//            ^^^----^^^-^^^------------------------------------ ***
    return /*...an object with the same shape as `obj`...*/;
}

使用方法完全符合您的问题。

Live on the playground

相关问题