網站搜尋

javascript - 有沒有辦法在 TypeScript 中操作 Object 類型的物件?


我有使用過 React 和 Typescript,並從 API 獲取資料。獲取資料後,它會被保存為 coin 物件。而在等待狀態時,可能沒有資料。所以,coin 可能為 null。如果 coin 是 null,那麼我們無法取得該物件的 image 欄位。以前有人處理過這個問題嗎?請給我一些建議。我沒有 Typescript 的經驗。這是我的程式碼:

import React, { Component } from 'react'
import axios from 'axios';
import CoinIcon from './CoinIcon';
interface CoinDetailProps{
    id:string;
}
interface CoinImage {
    thumb: string ;
    small: string ;
    large: string ;
  }
interface Coin {
    id: string,
    symbol: string,
    name: string,
    image: CoinImage | null,
    description: string
  }
  interface CoinState{
      coin : Coin;
      loaded: boolean;
  }
  
export class CoinDetail extends Component<CoinDetailProps,CoinState> {
    constructor(props) {
        super(props)
    
        
        const init = {} as Coin;
        this.state = {
             coin : init,
             loaded: false,
             
        }
    }
    loadData = () => {
        const {id} = this.props;
        const url = `https://api.coingecko.com/api/v3/coins/${id}`;
        
        axios.get(url)
          .then(response => {
            const data = response.data
            
            this.setState({
              coin: data,
              loaded: true
            })
          })
          .catch((error) => {console.log("Something went wrong. ", error)})
      }
      componentDidMount() {    
        this.loadData();
      }
    
      componentDidUpdate(prevProps, prevState) {    
        if (prevProps !== this.props) {
          this.loadData();
        }
      }
    render() 
    {
        const {loaded, coin} = this.state;
        console.log("coin image:" + coin.image.small)
        return (
            <div>
                <CoinIcon name={coin.name} symbol = {coin.symbol} image={coin.image.small} />
            </div>
        )
    }
}

export default CoinDetail

當我嘗試列印出來時像這樣:

console.log(coin.image.small) <=== error here: Object is possibly 'null'.

答案#1

您可以明確地檢查:

if (coin.image) {
    console.log(coin.image.small);
} else {
    // Do something else
}

或者你可以使用可選鏈結:

console.log(coin.image?.small);