简体   繁体   中英

How to map my string key to some possible enum values?

i have the following interface

export interface AuctionMOLQueryParams {
  filterAuctionDirection?: string;
}

because filterAuctionDirection can be one of three possible values i setted to be enum


export enum ProductDirection {
  upwards = 'A01',
  downwards = 'A02',
  all = 'All'
}

export interface AuctionMOLQueryParams {
  filterAuctionDirection?: ProductDirection;
}

the problem is that now when i try to use this object type

 let queryParams: AuctionMOLQueryParams = {
    filterAuctionDirection: ProductDirection.all,
 }

Types of property 'filterAuctionDirection' are incompatible. Type 'string' is not assignable to type 'ProductDirection' strong text

how can i solve this ? How can i map my filterAuctionDirection to be one of this three values and the type safey will still work correctly ?

TS2717: Subsequent property declarations must have the same type. 
Property 'filterAuctionDirection' must be of type 'string', but here has type 'ProductDirection'. 

If I understood your question correctly, you're defining the interface AuctionMOLQueryParams twice.
Initially you define the field filterAuctionDirection as string but later you're trying to mark it as ProductDirection .

If you're trying narrow a variable type of an externally declared interface (in this example AuctionMOLQueryParams ) you have to define a new interface extending of it.

Example for your use case:

export interface AuctionMOLQueryParams {
    filterAuctionDirection?: string;
}

export enum ProductDirection {
    upwards = 'A01',
    downwards = 'A02',
    all = 'All'
}

export interface MyAuctionMOLQueryParams extends AuctionMOLQueryParams {
    filterAuctionDirection?: ProductDirection;
}

let queryParamsValid1: MyAuctionMOLQueryParams = {
    filterAuctionDirection: ProductDirection.all,
}

let queryParamsInvalid2: MyAuctionMOLQueryParams = {
    filterAuctionDirection: "My",
}

let queryParamsInvalid1: MyAuctionMOLQueryParams = {
    filterAuctionDirection: "All",
}

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