简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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