我正在尝试遍历一个对象,其中键都是枚举中的case,值是any
类型(使用Typescript)。当对象中的值是预定义的常量时,这可以很好地工作,但其中一个值需要使用提供的字符串来生成返回对象。有什么方法可以在Typescript中完成此操作吗?我将在下面展示我所做的事情的简化示例。
对象常量
export const injected = new InjectedConnector({
supportedChainIds: [1, 3, 4, 5, 42],
});
export const walletconnect = new WalletConnectConnector({
rpc: RPC_URLS,
chainId: 1,
bridge: 'https://bridge.walletconnect.org',
qrcode: true,
});
export const walletlink = new WalletLinkConnector({
url: RPC_URLS[1],
appName: 'web3-react example',
supportedChainIds: [1, 3, 4, 5, 42, 10, 137, 69, 420, 80001],
});
export const magic = (email: string) => {
return new MagicConnector({
apiKey: 'apiKey',
chainId: 1,
email: email,
});
};
要在前端循环访问的枚举和对象
enum ConnectorNames {
Injected = 'MetaMask',
WalletConnect = 'WalletConnect',
WalletLink = 'Coinbase Wallet',
Magic = 'Email',
}
const connectorsByName: { [connectorName in ConnectorNames]: any } = {
[ConnectorNames.Injected]: injected,
[ConnectorNames.WalletConnect]: walletconnect,
[ConnectorNames.WalletLink]: walletlink,
// Would like to give magic an associated string value to pass into magic const above,
// somehting like `magic(test@gmail.com)`
[ConnectorNames.Magic]: magic,
};
前端TSX
const TestComponent = () => {
const [connector, setConnector] = useState<any>(null);
const testString = 'Hello, World!';
return (
<>
{Object.keys(connectorsByName).map((name) => {
// Would like to pass in test string to the connector/name in some way, and have magic
// consume it and the other 3 enum cases that dont need the associated value ignore it
const currentConnector =
connectorsByName[name as keyof typeof connectorsByName];
return (
<div
className=" bg-white rounded-lg p-4 hover:cursor-pointer min-w-[25vw]"
key={name}
onClick={() => {
setConnector(currentConnector);
}}
></div>
);
})}
</>
);
};
export default TestComponent;
1条答案
按热度按时间fnvucqvd1#
必须对
Object.keys()
API的返回值使用类型Assert。请参见Why doesn't Object.keys return a keyof type in TypeScript?打字机游戏场