输入 { [x: string]: T[S]; } 不可分配给类型 'Partial<T>'
Type { [x: string]: T[S]; } is not assignable to type 'Partial<T>'
我有这段代码,很简单:
interface A {
z: string;
y: number;
}
let newA = <T, S extends keyof T>(key: S, value: T[S]): Partial<T> => {
return {[key]: value};
}
我看到一条错误消息:
Type '{ [x: string]: T[S]; }' is not assignable to type 'Partial<T>'
我可以假设问题与 {}
有关,它总是将 key
映射为 string
但即使有明确的类型说那应该是 string
我没有结果
只有一个可行的解决方案是删除 Partial<T>
,但这不是一个好办法
希望能得到专家级typescript
大佬的解答,能描述一下这个问题的机理,也能得到这种情况的解决办法
注意! 该问题仅与一般情况有关。没有它一切都会好起来的。
您不需要使用部分。具有计算键的对象总是被推断为 {[prop:string]:any infered type}
您可以重载您的函数以避免此类行为:
type Json =
| null
| string
| number
| boolean
| Array<JSON>
| {
[prop: string]: Json
}
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value): Record<Key, Value>
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value) {
return { [key]: value };
}
const result = record('a', 42) // Record<"a", 42>
我有这段代码,很简单:
interface A {
z: string;
y: number;
}
let newA = <T, S extends keyof T>(key: S, value: T[S]): Partial<T> => {
return {[key]: value};
}
我看到一条错误消息:
Type '{ [x: string]: T[S]; }' is not assignable to type 'Partial<T>'
我可以假设问题与 {}
有关,它总是将 key
映射为 string
但即使有明确的类型说那应该是 string
我没有结果
只有一个可行的解决方案是删除 Partial<T>
,但这不是一个好办法
希望能得到专家级typescript
大佬的解答,能描述一下这个问题的机理,也能得到这种情况的解决办法
注意! 该问题仅与一般情况有关。没有它一切都会好起来的。
您不需要使用部分。具有计算键的对象总是被推断为 {[prop:string]:any infered type}
您可以重载您的函数以避免此类行为:
type Json =
| null
| string
| number
| boolean
| Array<JSON>
| {
[prop: string]: Json
}
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value): Record<Key, Value>
function record<Key extends PropertyKey, Value extends Json>(key: Key, value: Value) {
return { [key]: value };
}
const result = record('a', 42) // Record<"a", 42>