简体   繁体   English

Typescript 接口中的强制类型

[英]Enforcing types in Typescript interface

I have a interface for typing that looks like the following我有一个输入界面,如下所示

interface Bob{
    a: number;
    b: number;
    c: number;
}

However, I don't really want number as any number can be valid.但是,我真的不想要数字,因为任何数字都可以是有效的。 How can I enforce the type of Bob to be numbers strictly in a JSON file like the following.如何在 JSON 文件中严格强制 Bob 的类型为数字,如下所示。

{
  "None": -1,
  "foo": 22,
  "moo": 55,
  "raar": 13,
  "zaar": 2,
  "bar": 0,
  "fooboo": 22,
  "mooboo": 1000,
}

That JSON contains around 200 entries hence doing a manual typedef is not optimal. JSON 包含大约 200 个条目,因此执行手动 typedef 不是最佳选择。

What I aim to achieve我的目标是什么

const myvar: Bob;
myvar.a = 2222 // this should throw an error as this number is not defined in the JSON
myvar.b = -1 //this is ok as it is in the JSON

Thanks!谢谢!

Thanks to @zerkms for the answer.感谢@zerkms 的回答。

const json = {
  "None": -1,
  "foo": 22,
  "moo": 55,
  "raar": 13,
  "zaar": 2,
  "bar": 0,
  "fooboo": 22,
  "mooboo": 1000,
} as const;

type $Values<T extends object> = T[keyof T];
type supportedNumbers = typeof json[keyof typeof json];

interface Bob{
    a: supportedNumbers;
    b: supportedNumbers;
    c: supportedNumbers;
}

const NiceBob: Bob = {
  a: 3909, //error
  b: 319039, //error
  c: -1 //no error
};

Example can be found here示例可以在这里找到

Docs can be found here文档可以在这里找到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM