[英]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.