[英]TypeScript: Record-style type based on generic type describing arbitrary fields and their required types
我试图表达我的类型,以便当我这样调用我的代码时:
type Topics = {
documentList: Document[];
};
const TopicsContainer = useTopicsContainer<Topics>(['documentList']);
作为参数传递给useTopicsContainer
的数组被限制在Topics
中定义的字段。 useTopicsContainer
的示例实现如下:
const useTopicsContainer = <TopicsTypes>(
topics: (keyof TopicsTypes)[]
): TopicsState<TopicsTypes> => {
const initialState: TopicsState<TopicsTypes> = {};
const [topicsState, setTopicsState] = useState<TopicsState<TopicsTypes>>(
initialState
);
// some code mutating the state by calling setTopicsState, like e.g.
setInterval(
() =>
setTopicsState(
Object.fromEntries(
topics.map((topic) => [topic, createRandomDocument()])
)
),
1000
);
return topicsState;
};
我想从泛型TopicsTypes
派生TopicsState
类型。 到目前为止,我已经尝试过:
type TopicsState<TopicTypes> = Record<
keyof TopicTypes,
TopicTypes[keyof TopicTypes]
>;
但这会产生TS2322: Type '{}' is not assignable to type 'TopicsState '.
对于const initialState: TopicsState<TopicsTypes> = {};
另一种尝试:
interface TopicsState<TopicTypes> {
[topic: keyof TopicTypes]: TopicTypes[keyof TopicTypes];
}
…但这会导致TS1023: An index signature parameter type must be either 'string' or 'number'.
为topic
键。 我的想法已经不多了……如果你想给这个 go,下面是一个沙箱,上面的所有代码都拼凑在一起。 谢谢!
正如Alex Wayne所建议的,将Partial
添加到TopicsState
允许一个空的 object 文字成为TopicsState
。 我已经用它更新了 CodeSandbox 示例。 唯一剩下的问题是,现在我无法为topicsState
中的字段赋值,得到Type '{ [k: string]: Document; }' is not assignable to type 'Partial<Record<keyof TopicsTypes, TopicsTypes[keyof TopicsTypes]>>'.ts(2345)
Type '{ [k: string]: Document; }' is not assignable to type 'Partial<Record<keyof TopicsTypes, TopicsTypes[keyof TopicsTypes]>>'.ts(2345)
。 从好的方面来说, App.tsx
中消费者端的类型检查完全符合预期:
const TopicsContainer = useTopicsContainer<Topics>(["documentList"]);
const documentList: Document[] = TopicsContainer.documentList || [];
如果我将documentList: Document[]
更改为documentList: string
,我会得到所需的Type 'Document[]' is not assignable to type 'string'.ts(2322)
。 有没有办法放松useTopicsContainer
实施中的约束?
我追求的类型如下:
type ValueOf<T> = T[keyof T];
type TopicsState<TopicTypes> = Partial<
Record<keyof TopicTypes, ValueOf<TopicTypes>>
>;
有了它,我现在可以像这样使用它:
type Topics = {
documentList: Document[];
};
const TopicsContainer = useTopicsContainer<Topics>(["documentList"]);
const documentList: Document[] = TopicsContainer.documentList || [];
这样, TopicsContainer
知道"documentList"
键下的类型是Document[]
。
为后代:
// useTopicsContainer.ts
import { useEffect, useState } from "react";
import io from "socket.io-client";
type ValueOf<T> = T[keyof T];
type TopicsState<TopicTypes> = Partial<
Record<keyof TopicTypes, ValueOf<TopicTypes>>
>;
type KeysOfTopicsState<TopicTypes> = Extract<keyof TopicTypes, string>[];
const client = io("/topics");
const useTopicsContainer = <TopicsTypes>(
topics: KeysOfTopicsState<TopicsTypes>
): TopicsState<TopicsTypes> => {
const initialState: TopicsState<TopicsTypes> = {};
const [topicsState, setTopicsState] = useState<TopicsState<TopicsTypes>>(
initialState
);
// some code mutating the state by calling setTopicsState, like e.g.
useEffect(() => {
const topicListeners = Object.fromEntries(
topics.map((topic) => [
topic,
(topicData: ValueOf<TopicsTypes>) => {
setTopicsState((oldState) => ({
...oldState,
[topic]: topicData
}));
}
])
);
topics.forEach((topic) => {
client.on(topic as string, topicListeners[topic]);
});
return () => {
topics.forEach((topic) => {
client.off(topic, topicListeners[topic]);
});
};
});
return topicsState;
};
export default useTopicsContainer;
// App.tsx
import React from "react";
import useTopicsContainer from "./useTopicsContainer";
type Topics = {
documentList: Document[];
};
export default function App() {
const TopicsContainer = useTopicsContainer<Topics>(["documentList"]);
const documentList: Document[] = TopicsContainer.documentList || [];
console.log({ documentList });
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
感谢Alex Wayne和jcalz的建议,橡皮擦并保持我的例子直截了当!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.