In TypeScript, any
is an escape hatch from the type system. Or maybe a black hole that eats up every other type it touches. It is treated both as a top type (any value can be assigned to a variable of type any
) and a bottom type (a value of type any
can be assigned to a variable of any type). You might even say it is both a supertype of string
and a subtype of string
. That's generally unsound; all types become assignable to all other types if you use any
, but it's a useful way to opt out of the type system and make assignments that the compiler would otherwise prevent.
If you want a real top type which isn't a black hole, use unknown
. You already know that never
is the real bottom type. For more interesting reading on this, see Microsoft/TypeScript#9999.
For your code, try:
type PropertyMap = {
prop1: {
name: "somename";
required: unknown; // top type
};
prop2: {
name: "someothername";
required: never; // bottom type
}
}
type RequiredOnly = {
[P in keyof PropertyMap]: PropertyMap[P] & PropertyMap[P]["required"]
}
Now RequiredOnly["prop1"]
should act like what you want.
Hope that helps; good luck!
Any help appreciated.
I see what you did there.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…