English 中文(简体)
• 如何将一只假体的钥匙限制在像样的结合中? [复制]
原标题:How to limit the key of an obejct type to be part of a union in TypeScript? [duplicate]
  • 时间:2023-12-28 02:36:21
  •  标签:
  • typescript

我拥有服务器类型,例如:

type Union =  A  |  B  |  C ;

然后,我想作一模棱两可的类型,其钥匙将成为这一联盟的一部分,例如:

// Only use  A  and  B  from union
const myObject: { [K in Union]: number } = {
  A: 1,
  B: 2,
} as const;

我也想使我的抱负趋于一致,因此我可以期望:

console.log(myObject.A); // To be OK
console.log(myObject.C); // To be Error

然而,当我使用<代码>[K in Union]时,汇编者会发现以下错误:

财产 C在类型{仅读为A:1;读为B:2;}但需要的是类型{A:编号;B:编号;C:编号;} 。

我只能从该联盟中挑选一部分类型?

我的目的是宣布只拥有特定工会类型的一部分钥匙的物体。

问题回答
type Union =  A  |  B  |  C ;

const myObject = {
  A: 1,
  B: 2,
} as const satisfies { [K in Union]?: number | unknown };

我认为应该这样做。





相关问题
store data in memory with nestjs

I am trying to persist some data in my nestjs server so I can then use that data in my client app through http requests. I have created a products.service.ts file with the function getAllData() that ...

React Hook Form Error on custom Input component

I am having a problem when I use react hook form + zod in my application, in short the inputs never change value and I get the following error in the console: Warning: Function components cannot be ...

Updatable promises using proxy in JavaScript

EDIT: I ve updated this question, and the old question is moved here. A POC can be found on this jsfiddle or the snippet below GOAL: The goal here is to make or rather simulate a promise that can be ...

热门标签