简体   繁体   English

如何将任何类型值的 object 转换为字符串值的 object (Typescript)?

[英]How to convert object of any type values, to object of string values (Typescript)?

I have an object.我有一个 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.我知道 object 中的值都是字符串,但我不想强制类型转换。

// 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 .相反,我想以正确的方式推断它,使用typescript 谓词 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?我应该能够将string分配给T[P] = any ,对吧? What am I doing wrong?我究竟做错了什么? Is there any alternative solution to this?有没有其他解决方案?

In order to make it work, you need to infer just a set of keys instead of whole object:为了使其工作,您只需要推断一组键而不是整个 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 K - 用于键推断

Also I have added isString custom typeguard我还添加了isString自定义类型保护

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM