You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript中基于已有Interface创建新Interface为何失效?

Why Your Mapped Interface Isn't Working (and How to Fix It)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 11:17:34