[英]"keyof typeof" on Generics
您好,我的通用打字有些困難。
interface ReturnValue {
keyA: string,
keyB: string
}
interface FilterA {
keyA: boolean;
}
interface FilterB {
keyB: boolean;
}
const func = function<T>(args: T) : Pick<ReturnValue, keyof typeof args> {
const res :Pick<ReturnValue, keyof typeof T> = {};
Object.keys(args).map(key => {
res[key] = key
})
return res;
}
console.log(func({keyB: true}).keyB); // should work
console.log(func({keyA: true}).keyA); // should work
console.log(func({keyA: true}).keyB); // should not work
console.log(func({keyC: true}).keyC); // should not work
但我有這個錯誤:
Type 'keyof T' does not satisfy the constraint 'keyof ReturnValue'.
Type 'string | number | symbol' is not assignable to type 'keyof ReturnValue'.
Type 'string' is not assignable to type 'keyof ReturnValue'.
Type 'keyof T' is not assignable to type '"keyB"'.
Type 'string | number | symbol' is not assignable to type '"keyB"'.
Type 'string' is not assignable to type '"keyB"'.(2344)
有任何想法嗎?
當我使用 function 調用它工作正常時,我只能訪問我作為 arguments 提供的內容,但 TS 仍然顯示此錯誤。
上下文是 GraphQl。 我的輸入是 object ,其中每個鍵的值為true
或false
。 從這個 object 我將構建一個 GQL 字符串查詢,獲取到 api,返回將具有相同的結構,但值不會是boolean
,而是string
。
它在這里使用Array.prototype.reduce
和映射類型:
interface FilterA {
keyA: boolean;
}
interface FilterB {
keyB: boolean;
}
type Filters = FilterA | FilterB
type Reduce<Obj> = {
[Prop in keyof Obj]: Prop
}
const func = <Obj extends Filters>(args: Obj) =>
Object.keys(args).reduce((acc, key) => ({
...acc,
[key]: key
}), {} as Reduce<Obj>)
func({ keyB: true }).keyB; // ok
func({ keyA: true }).keyA; // ok
func({ keyA: true }).keyB; // error
func({ keyC: true }).keyC // error
我使用了這種方法的不可變版本,不是因為它更好。 我只是更喜歡不可變的數據結構。
更新
來自評論的替代版本的Reduce
示例:
type Reduce<Obj> = {
[Prop in keyof Obj]: Prop extends keyof ReturnValue ? ReturnValue[Prop] : never
}
interface ReturnValue {
keyA: string,
keyB: string
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.