我构建了一个函数,它接受一个对象和该对象的一个字符串键。但是在函数体中,它不会让我用不同的字符串设置对象的值。
const setAndGetString = <K extends string, T extends Record<Exclude<string, K>, any>>(
obj: T & Record<K, string>,
key: K
): string => {
obj[key] = "foo" // Type 'string' is not assignable to type '(T & Record<K, string>)[K]'.
return obj[key] // okay
}
有没有一种方法可以调整签名以使作业生效? (是的,我可以在作业中进行转换,但该解决方案不是很好)。
最佳答案
你很接近。
考虑这个例子:
/**
* Obtain a union of all values of record
*/
type Values<T> = T[keyof T]
/**
* Obtain a union of all object keys which coresponds to strings
*/
type StringProperty<T> = Values<{
[Prop in keyof T]: T[Prop] extends string ? Prop : never
}>
const setAndGetString = <
Obj extends Record<PropertyKey, unknown>,
Key extends StringProperty<Obj>
>(obj: Obj & Record<Key, string>, key: Key) => {
const result = obj[key].charAt // ok
return obj[key] // okay
}
const obj = {
a: 'a',
b: 42
}
setAndGetString(obj, 'a') // ok
setAndGetString(obj, 'b') // expected error
关于typescript - 为什么 typescript 识别出对象的类型是字符串时,不让我将对象的值设置为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73885923/