例如:
type ObjectOf<T> = { [k: string]: T };
type MapObj<Obj extends ObjectOf<any>> = {
[K in keyof Obj]: Obj[K] extends string
? 'string'
: 'other';
};
type Foo = MapObj<{
a?: 'a',
b: 'b',
}>;
我希望
Foo
的类型为:
{
a?: 'string',
b: 'string',
}
但实际上是:
{
a?: 'other' | undefined,
b: 'string',
}
我该如何解决这个问题?
我认为你所拥有的应该有效。尝试在 tsconfig 中进行设置,将类型缩小到您想要的范围:
"exactOptionalPropertyTypes": true
如果没有该选项,我认为无论何时评估类型,都会将
undefined
添加到可选类型,因为该设置是为了严格强制哪些属性可以显式设置为 undefined
与根本不设置属性.