英文:
How to convert object of any type values, to object of string values (Typescript)?
问题
我有一个对象。
/*
type A = {
property1: any;
property2: any;
}
*/
我知道对象中的值都是字符串,但我不想强制类型转换。
// 我不想这样做
const obj2 = obj1 as Record<keyof typeof obj1, string>
相反,我想以正确的方式推断它,使用typescript predicates。这是我的尝试。
function getIsCorrectType<T extends Record<string, any>>(
obj: T
): obj is Record<keyof T, string>{
return true; // 假设我手动检查了每个值是否为字符串
}
然而,我现在遇到了一个错误
A type predicate的type必须可分配给其parameter的type。
Type 'Record<keyof T, string>' is not assignable to type 'T'.
'Record<keyof T, string>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record<string, any>'.
Type 'string' is not assignable to type 'T[P]'.
对我来说这听起来很奇怪。我应该能够将string
分配给T[P] = any
,对吗?我做错了什么?是否有其他解决方案?
<details>
<summary>英文:</summary>
I have an object.
let obj1: A;
/*
type A = {
property1: any;
property2: any;
}
*/
I know that the values in the object are all strings, but I **don't** want to forcefully typecast.
// I don't want to do this
const obj2 = obj1 as Record<keyof typeof obj1, string>
Instead, I want to infer it in the right way, using **typescript predicates**. This is my attempt to do it.
function getIsCorrectType<T extends Record<string, any>>(
obj: T
): obj is Record<keyof T, string>{
return true; // assume that I manually checked each value to be a string
}
However I now get an error
A type predicate's type must be assignable to its parameter's type.
Type 'Record<keyof T, string>' is not assignable to type 'T'.
'Record<keyof T, string>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record<string, any>'.
Type 'string' is not assignable to type 'T[P]'.
To me this sounds crazy. I should be able to assign `string` to `T[P] = any`, right? What am I doing wrong? Is there any alternative solution to this?
</details>
# 答案1
**得分**: 2
```typescript
为了使其工作,您只需要推断一组键,而不是整个对象:
const isString = (value: unknown): value is string => typeof value === 'string'
const getIsCorrectType = <K extends string>(
obj: Record<K, unknown>
): obj is Record<K, string> =>
Object.values(obj).every(isString)
const x = getIsCorrectType({ 1: 'sdf' })
K - 用于键的推断
还添加了isString自定义类型保护
英文:
In order to make it work, you need to infer just a set of keys instead of whole object:
const isString = (value: unknown): value is string => typeof value === 'string'
const getIsCorrectType = <K extends string>(
obj: Record<K, unknown>
): obj is Record<K, string> =>
Object.values(obj).every(isString)
const x = getIsCorrectType({ 1: 'sdf' })
K
- is used for keys inference
Also I have added isString
custom typeguard
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论