我希望对接口中的嵌套属性执行类型判断,并具有以下代码
type PathImpl<T, K extends keyof T> = K extends string
? T[K] extends Record<string, any>
? `${K}.${Path<T[K]>}` | K
: K
: never;
export type Path<T> = PathImpl<T, keyof T>;
export interface User {
name: string;
age: number;
dimensions: {
height: number;
weight: number;
}
address?: {
street: string;
city: string;
state: string;
};
}
const validPath: Path<User> = 'name'; // Works fine
const alsoValidPath: Path<User> = 'address'; // Works fine
const nestedValidPath: Path<User> = 'dimensions.height'; // Yay, works fine!
const doesntWorkPath: Path<User> = 'address.street'; // Doesn't work because address is optional
有没有一种方法可以设计Path类型来允许"address.street"也是有效的,尽管address是可选的?