无法获取嵌套的JSON对象属性打字稿

阿里·戴维斯(Ari Davis)

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

如果我管理此代码,它将输出所有货币

((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)

亚历克斯·韦恩

您应该为数据创建一个类型。因为它来自外部来源,所以打字稿无法推断出来。然后解析您的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)

打字稿操场上的工作演示

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章