TS中两种对象类型的深度交集类型

Deep intersection type of two object types in TS

deep/recursive 两种对象类型的交集是否有类似“&”的内容?意思是只允许访问存在于所有合并类型中的属性。

这是我想要做的:

// Defined in its own file
const en = {
  "welcome": {
    "hello": "Hello",
    "world": "World"
  }
}

// Defined in its own file
const hu = {
  "welcome": {
    "hello": "Helló világ"
  }
}

// How to write this type?
// Should be deep intersection,
// meaning only mutually available properties allowed
let locale: typeof en & typeof hu

//  Using a Webpack resolve.alias
//  resolve.alias.locales = path.resolve(
//    __dirname,
//    `locales/${process.env.NEXT_PUBLIC_LOCALE}`
//  )
//@ts-ignore
locale = {}

locale.welcome.world // This should NOT be available
locale.welcome.hello // This SHOULD be availeble

您需要使用 union 来获得两个的公共点。我知道它在语言上(维恩图明智)是相反的,但它是这样工作的。 (我强烈建议阅读@jcalz 对此答案的评论和链接,以便更好地解释为什么从类型分配的角度来看 &| 有意义。)

TS Playground

const en = {
  welcome: {
    hello: "Hello",
    world: "World",
  },
};

const hu = {
  welcome: {
    hello: "Helló világ",
  },
};

let locale = {} as typeof en | typeof hu;

// Error: Property 'world' does not exist on type '{ hello: string; world: string; } | { hello: string; }'.
locale.welcome.world; // This should NOT be available

// Works
locale.welcome.hello; // This SHOULD be availeble