如果我想映射对象值并且所有值都是基本类型,那么很简单:
type ObjectOf<T> = { [k: string]: T };
type MapObj<Obj extends ObjectOf<any>> = {
[K in keyof Obj]: Obj[K] extends string ? Obj[K] : 'not string';
};
type Foo = MapObj<{
a: 'string',
b: 123,
}>; // Foo is { a: 'string', b: 'not string' }
但是,当我将联合类型作为对象值时,TS的工作效果不如预期:
type AllPaths = '/user' | '/post';
type Props<Path extends AllPaths> = MapObj<{
path: Path,
}>;
function Fn<Path extends AllPaths>({ path }: Props<Path>) {
const path2: AllPaths = path;
}
我遇到了以下错误:
Type 'Path extends string ? Path : "not string"' is not assignable to type 'AllPaths'.
Type 'Path | "not string"' is not assignable to type 'AllPaths'.
Type '"not string"' is not assignable to type 'AllPaths'.
Type 'Path extends string ? Path : "not string"' is not assignable to type '"/post"'.
Type 'Path | "not string"' is not assignable to type '"/post"'.
Type 'string & Path' is not assignable to type '"/post"'.
因为联合类型的成员都是字符串,所以我希望MapObj
的输出仍然是字符串的联合类型。我该如何解决这个问题?
Path
,因为其他对象值需要使用它。 - Leo Jiang