簡體   English   中英

Typescript:解構 hash 時如何使用符號作為鍵

[英]Typescript: How to use a symbol as a key when destructuring a hash

type UseStateTuple<T> = [T,React.Dispatch<React.SetStateAction<T>>]
const StoreContext = createContext<IStore | null>(null)
interface IStore {
  people: UseStateTuple<string[]>
  // IStore could potentially have other useState tuples. Something like
  // posts: UseStateTuple<IPost[]> for example
}

interface Props {
  type: string        // this is the key that points to a useState tuple
  description: string // ignore this
}

export const AddPerson: React.FC<Props> = ({type, description}) => {
  const [input, setInput] = useState('')

  // useContext(StoreContext) returns an IStore object that I want to destructure.
  // In this context (no pun intended) "[type]:" should be evaluated to "people:", right?
  //
  // I can use:
  //   "{ people }"
  //
  // instead of
  //   "[type]: [data, setData]"
  //
  // and it works. Why is that? 
  const { [type]: [data, setData] } = useContext(StoreContext)!

  /*
  // This code works fine.
  const { people } = useContext(StoreContext)!
  const [data, setData] = people
  */

  // function continues....
}

/// JSX
<AddPerson type="people" description="Here is a description..." />

如果您需要有關此簡單useContext / useState和 Typescript 示例的更多信息,三個最相關的文件(以及整個項目)位於此處 我試圖將所有相關代碼都放在帖子中。

你可能想要

interface Props {
  type: keyof IStore        // this is the key that points to a useState tuple
  description: string // ignore this
}

通常要使用索引,索引表達式必須是keyof T類型,其中T是您要索引的任何類型。 或者換句話說,索引表達式必須可證明作為T的索引是有效的。

如果您將type更改為keyof IStore它將起作用:

import React, { createContext, useState, useContext } from 'react'

type UseStateTuple<T> = [T, React.Dispatch<React.SetStateAction<T>>]
const StoreContext = createContext<IStore | null>(null)
interface IStore {
  people: UseStateTuple<string[]>
  // IStore could potentially have other useState tuples. Something like
  // posts: UseStateTuple<IPost[]>
}

interface Props {
  type: keyof IStore        
  description: string 
}

export const AddPerson: React.FC<Props> = ({type, description}) => {
  const [input, setInput] = useState('')

  const { [type]: [data, setData] } = useContext(StoreContext)!

  return <div></div>
}

let d = () => <AddPerson type="people" description="Here is a description..." /> 

//error
let d2 = () => <AddPerson type="people2" description="Here is a description..." /> 

游樂場鏈接

您可能在調用 set 方法時遇到問題,因為它將是聯合類型,因此可能需要類型斷言。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM