首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法获取嵌套的JSON对象属性Typescript

无法获取嵌套的JSON对象属性Typescript
EN

Stack Overflow用户
提问于 2019-07-26 00:27:23
回答 1查看 1.7K关注 0票数 0

我想从https://api.exchangeratesapi.io/latest获得CAD值我已经使用了这么多类型的代码,它说"TypeError: Cannot read property 'CAD' of undefined"真的需要你的帮助,非常感谢。

如果我操控这段代码,它会输出所有的货币

代码语言:javascript
复制
((this.state.data as any).rates)

但是当我想要获取CAD货币时,它会显示错误

我已经尝试过这些代码:

代码语言:javascript
复制
((this.state.data as any).rates as any).CAD
(this.state.data as any)["Rates"]["CAD"];
(this.state.data as any)["Rates"].CAD;

我获取数据的方法是

代码语言:javascript
复制
interface IState {
  data?: object | null;
  isCurrency?: boolean;
  Currency?: string;
  Rate?: number;
}

export default class Header extends Component<{}, IState> {
  service: UserService = new UserService();
  state = {
    isCurrency: false,
    Currency: "USD",
    Rate: 1,
    data: [] = []
  };

  async componentDidMount() {
    let result = await this.service.getAllCurrency();
    this.setState({
      data: (result as Pick<IState, keyof IState>).data
    });
    console.log(result);
  }
}

1.4591 (基于最新API)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-26 01:12:35

您应该为您的数据创建一个类型。因为它来自外部来源,所以typescript无法推断这一点。然后解析您的JSON并将其转换为该类型。

代码语言:javascript
复制
// Create a type for the expernal data.
interface Data {
    rates: {
        [currency: string]: number
    }
    base: string
    date: string
}

// Result of `JSON.parse()` will be `any`, since typescript can't parse it.
const untypedData = JSON.parse(`{
  "rates": {
    "CAD": 1.4591,
    "HKD": 8.6851,
    "ISK": 135.9,
    "PHP": 56.797,
    "DKK": 7.4648
  },
  "base": "EUR",
  "date": "2019-07-25"
}`)

// Cast the untyped JSON to the type you expect it to be.
const data: Data = untypedData

// Use the data according to it's type.
alert(data.rates.CAD)

Working demo on typescript playground

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57206493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档