我有一个对象
let obj1: A;
/*
type A = {
property1: any;
property2: any;
}
*/
我知道对象中的值都是字符串,但我不想要强制类型转换
// I don't want to do this
const obj2 = obj1 as Record<keyof typeof obj1, string>
相反,我想以正确的方式推断它,使用typescript谓词. 这是我的尝试。
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
}
但是我现在得到一个错误
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]'.
对我来说这听起来很疯狂。我应该可以把string
分配给T[P] = any
,对吧?我做错了什么?有其他解决办法吗?
为了使它工作,您只需要推断一组键而不是整个对象:
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
自定义typeguard