iT邦幫忙

0

請問useState的型別應該怎麼設定比較好?

  • 分享至 

  • xImage

我的程式簡化後差不多長這樣

type Tfoo = {
  a: string,
  b: string,
  c: number,
  d: boolean,
}

const apiFoo = (): Tfoo => {
  return {
    a: "AA",
    b: "bb",
    c: 123,
    d: true,
  }
}

const useFoo = () => {
  const [data, setData] = useState<Tfoo | {}>({})
  const update = async () => {
    const res = await apiFoo()
    setData(res)
  }
  return { data, setData, update }
}

const Bar = () => {
  const { data, setData, update } = useFoo()
  if(!data.a) return null
  console.log(data.a)
}

在console.log(data.a) 會跳出錯誤

類型 '{} | Tfoo' 沒有屬性 'a'。
類型 '{}' 沒有屬性 'a'。ts(2339)

請問我應該怎麼處理這個錯誤?
我預期會出現undefined,也有對於undefined做處理
結果連 if(!data.a) 本身也跳這個錯誤

我希望避免以下面的方式處理
我希望避免a b c d以外的property出現

type Tfoo = {
  [key: string]: string | number | boolean
  a: string,
  b: string,
  c: number,
  d: boolean,
}

求各位經驗分享,謝謝

froce iT邦大師 1 級 ‧ 2022-10-13 13:03:30 檢舉
if(!data.a)改成
if (!data?.a)

> 我希望避免a b c d以外的property出現
應該沒辦法。
接口只能確保裡面一定有什麼,不能確保額外不能加啥。
畢竟在抽象化的過程裡不會需要對額外的屬性做處理,只需要確保裡面的接口有實現就好。
harry xie iT邦研究生 1 級 ‧ 2022-10-13 13:37:01 檢舉
同上,使用 optional operator 解決即可
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
小哈片刻
iT邦研究生 5 級 ‧ 2022-10-13 21:27:17
最佳解答

我猜你想要的應該是這樣的Tfoo,表示這個資料不能有abcd以外的東西,但不一定四個屬性都要有

type Tfoo = {
  a?: string,
  b?: string,
  c?: number,
  d?: boolean,
}

然後在useState時,就不用|{}了

const [data, setData] = useState<Tfoo>({})
silarce iT邦新手 5 級 ‧ 2022-10-14 09:11:49 檢舉

這樣可以用,感謝

我要發表回答

立即登入回答