2017-04-25 41 views
0

我希望将any类型的对象转换为符合特定接口的对象(如ApiResponse),并对其进行适当的错误处理没有必要的特性才能成为这个对象。类型为any的对象来自JSON有效内容,来自JSON.parse或等效内容。理想情况下,我也希望处理这种转换的一些适当的错误处理。我提出了以下方法,但不确定它是否正确使用TypeScript或利用最佳模式。安全地将任何对象转换为符合TypeScript接口的对象

回答

-1
` 

export interface ApiResponse { 

    code: number 
    type: string 
    message: string 

} 



export function readApiResponse(json: any): ApiResponse { 

    if (!json.hasOwnProperty('code')) { 
     throw 'No code property' 
    } 

    if (!json.hasOwnProperty('type')) { 
     throw 'No type property' 
    } 

    if (!json.hasOwnProperty('message')) { 
     throw 'No message property' 
    } 

    return json 
} 


loadData() { 
     fetch("data.json") 
      .then(response => response.json()) 
      .then((json: any) => { 

       console.log(json) 

       let r = readApiResponse(json) 

       console.log(r) 

       this.setState({message : r.message }) 

      }) 
      .catch ((error) => { 
       console.log(error) 
      }) 

    } 

`

+0

嗯。我不确定为什么这个问题和方法被低估。这特别确保从JSON生成的对象具有为符合接口而定义的正确属性。我想,因为在运行时,在转译之后,接口的概念不再使用。 –

+0

我不是down-voter,但我不清楚这将如何扩展到嵌套类型,可选值,具有其他限制的值的真实大小的API。如果响应有额外的字段,它也不会出错......(尽管它对我来说不应该是......) –

+0

哦,如果类型不符合预期,它实际上并不会出错。所以'{code:“foo”,类型:11,message:[]}''会通过你的'readApiResponse'很好。 –