json - 无法获取嵌套 JSON 对象属性 Typescript

标签 json reactjs typescript api

我想从 https://api.exchangeratesapi.io/latest 获取 CAD 值 我已经使用了很多类型的代码,它说“TypeError:无法读取未定义的属性'CAD'” 真的需要您的帮助,非常感谢。

如果我控制台此代码,它会输出所有货币

((this.state.data as any).rates)

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

我已经尝试过这些代码:

((this.state.data as any).rates as any).CAD
(this.state.data as any)["Rates"]["CAD"];
(this.state.data as any)["Rates"].CAD;

我获取数据的方式是

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)

最佳答案

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

// 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

关于json - 无法获取嵌套 JSON 对象属性 Typescript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57206493/

相关文章:

angular - 修改 TestBed.overrideComponent 中定义的组件

typescript - 如何为 TypeScript 定义文件导入文件

sql - postgres 从函数返回 json

angular - 如何在 Angular 中管道/映射 Observable

json - 在 elasticsearch 中索引平面 XML 文件

javascript - React - 状态不一致

javascript - 在 React Hook 的 setState() 调用中访问当前状态时,prevState 变量是状态对象的副本还是直接引用?

node.js - `isomorphic-fetch` 和 `isomorphic-unfetch` npm 包有什么区别

php - 消息 : file_get_contents(sso. json):无法打开流:没有这样的文件或目录

php - 用php将JSON文件导入MYSQL数据库