我很不确定这是否可能,但我已经很接近了。
如果我有这个对象/形状:
如果我有这个对象/形状:
export const initialState: State = {
foods: {
filter: '',
someForm: {
name: '',
age: 2,
},
someFormWithoutAnAge: {
name: '',
},
}
};
declare function pickAForm<R extends keyof State, S extends keyof State[R]>(key1: R, key2: S): void;
该函数的运行良好,我可以使用类型安全地调用 pickAForm("foods", "someForm")
,如果我执行 pickAForm("foods","somePropertyThatDoesntExist")
将会报错。
然而,我想要增加额外的安全性,即只能选择具有特定形状的项目。例如:someForm
应该可以通过,但 someFormWithoutAnAge
应该失败,因为您选择的任何内容都必须具有一个年龄属性。可以像这样:
declare function pickAFormWithAge<R extends keyof State, S extends keyof State[R], T extends State[R][S] & {age: number}>(key1: R, key2: S): void;
但是我并不确定如何开始。简而言之:
pickAFormWithAge('foods', 'someForm') // Passes
pickAFormWithAge('foods', 'someFormWithoutAge') // Should fail, does not look like {age: number}
pickAFormWithAge('foods', 'blah') // Should fail, not a key
State
的定义,会很有帮助。 - Nitzan Tomertype State = typeof initialState
。 - silviogutierrez类型“"someForm"”的参数不能赋给类型“never”的参数。
- Nitzan TomerS
参数指定为S extends keyof (State[R] & { age: number; })
。 - timocov