简体   繁体   English

如何使用接口属性强制对象类型-值

[英]How to enforce object type with interface property - value

I have this interface 我有这个界面

interface SUser {
  ID: number;
  NAME: string;
  MAIL: string;
  PASSWORD: string;
  GENDER: number;
  BIRTHDATE: string;
  ID_FB: string;
  CREDIT: number;
  ID_REFERRAL: number;
}

And I want to have a type describing an object and ensuring my object matches the key and value of one of my interface properties. 而且我想要一种描述对象的类型,并确保我的对象与我的接口属性之一的键和值匹配。

I tried the following : 我尝试了以下方法:

type fieldType = { [K in SUser]: string | number };

I set a field object to only allow a key from SUser ok, but I want to get an error if I set the value to a string if the key is ID for example. 我将字段对象设置为仅允许来自SUser的键,但例如,如果键的值是ID ,则将值设置为字符串,则想得到一个错误。

Basically I want to enforce a key - value pair based on my interface. 基本上,我想基于我的界面强制执行键-值对。

With the previous code I get the following error, and value type is not enforced : 使用前面的代码,我得到以下错误,并且不强制使用值类型:

Type 'SUser' is not assignable to type 'string | number | symbol'.
  Type 'SUser' is not assignable to type 'symbol'.

Any help on this subject ? 在这个问题上有帮助吗?

你会这样使用

type fieldType = Partial<SUser>;

To make your code compile, you would do: 为了使代码编译,您可以执行以下操作:

type fieldType = { [K in keyof SUser]: string | number };

But I'm not sure how you're going to use it since it would expand to: 但是我不确定您将如何使用它,因为它将扩展为:

type fieldType = {
  ID: string | number;
  NAME: string | number;
  MAIL: string | number;
  PASSWORD: string | number;
  GENDER: string | number;
  BIRTHDATE: string | number;
  ID_FB: string | number;
  CREDIT: string | number;
  ID_REFERRAL: string | number;
}

and that would not give you the error you want. 那不会给你你想要的错误。

You may potentially want to use Partial<SUser> to create a type with all properties optional 您可能可能希望使用Partial <SUser>来创建具有所有属性可选的类型

type fieldType = {
  ID?: number;
  NAME?: string;
  MAIL?: string;
  PASSWORD?: string;
  GENDER?: number;
  BIRTHDATE: string;
  ID_FB?: string;
  CREDIT?: number;
  ID_REFERRAL?: number;
}

I'm assuming this is because you would like to pass in a subset of properties in some cases but in others, you require a full field. 我假设这是因为在某些情况下您想传入属性的子集,但在其他情况下,则需要完整的字段。 See TypeScript partial interface object 请参见TypeScript部分接口对象

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

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