努力理解打字稿的减少
假设我将实用程序类型定义为具有所有属性作为字符串的对象
type Stringify<T> = {
[P in keyof T]: string;
};
,我想定义一个将对象的任何属性转换为字符串的函数,例如
function stringify<T>(obj: T): Stringify<T> {
return Object.entries(obj).reduce((acc, [k, v]) => {
acc[k] = `${v}`;
return acc;
}, {});
}
我不知道如何定义在 我一直在阅读有关铸造,类型防护和功能过载的每个cicle,
.reduce<Partial<T>>((acc, [k, v]) => /* ... */) // type Partial<T> is not assignable to type Stringify<T>
.reduce((acc: Partial<T>, [k, v]) => /* ... */) // type Partial<T> is not assignable to type Stringify<T>
.reduce(/* ... */, {} as Partial<T>) // type Partial<T> is not assignable to type Stringify<T>
.reduce(/* ...*/
acc[k] = `${v}`; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Stringify<T>'. No index signature with a parameter of type 'string' was found on type 'Stringify<T>'
}, {} as Stringify<T>)
但我仍然无法为这样一个简单的示例提供解决方案。
Let's say I define a Utility type to have an object with all attributes as string
type Stringify<T> = {
[P in keyof T]: string;
};
and I want to define a function that converts any attribute of an object to string such as
function stringify<T>(obj: T): Stringify<T> {
return Object.entries(obj).reduce((acc, [k, v]) => {
acc[k] = `${v}`;
return acc;
}, {});
}
I can't figure out how to define the accumulator that is being fulfilled at every cicle in the reduce callback
.reduce<Partial<T>>((acc, [k, v]) => /* ... */) // type Partial<T> is not assignable to type Stringify<T>
.reduce((acc: Partial<T>, [k, v]) => /* ... */) // type Partial<T> is not assignable to type Stringify<T>
.reduce(/* ... */, {} as Partial<T>) // type Partial<T> is not assignable to type Stringify<T>
.reduce(/* ...*/
acc[k] = `${v}`; // Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Stringify<T>'. No index signature with a parameter of type 'string' was found on type 'Stringify<T>'
}, {} as Stringify<T>)
I've been reading about casting, type guards, and function overload but I still can't arrive to a solution to such a simple example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
stringify
generic基本上与实用程序类型record
进行相同的作业。您可以使用通用参数充当
Record&lt;字符串,任何&gt;
的速记,以节省一些详细的杂句。更新:键入返回值作为record&lt; string,string&gt;
Your
Stringify
generic is essentially doing the same job as the utility typeRecord
.You can use the generic argument to act as a shorthand for
Record<string, any>
to save a bit of verbosity.Update: typing return value as Record<string, string>