TypeScript中基于已有Interface创建新Interface为何失效?
Great question—let’s break down the two key issues preventing your code from working as expected:
1. Mapped syntax isn’t supported in interface declarations
TypeScript’s mapped type pattern ([K in keyof A]) is designed to work with type aliases, not interfaces. Interfaces have strict structural rules and don’t allow dynamic key iteration syntax directly. This is why your original interface B declaration fails.
2. You’re using the wrong boolean type
Boolean (uppercase) refers to the JavaScript wrapper object type, which is almost never what you want for property types. The primitive boolean type you need for true/false values is lowercase boolean.
The Fixed Solution
Replace the interface for B with a type alias using the correct mapped syntax and primitive type:
interface A { x: string; y: string; z: string; // maybe later something more } // This dynamically generates the type you want! type B = { [K in keyof A]: boolean; };
Now B will automatically mirror all keys from A with boolean types. If you add new properties to A later, B will update to include them without any extra code—exactly what you were aiming for.
Bonus: If You Really Need an Interface
While a type alias is the cleanest approach here, if you must use an interface for specific reasons, you can extend the mapped type like this:
interface B extends { [K in keyof A]: boolean } {}
But this is unnecessary in most cases—the type alias is simpler and achieves the same result.
内容的提问来源于stack exchange,提问作者Rozrewolwerowany rewolwer

