Noah Bergh
Noah Bergh

Reputation: 495

Is there any way to type annotate a parameter must be part of an interface

I have the following function

export const getCreateProductsError = (index: number, err: string) => createSelector(
  getCreateFeatureState,
  state => state.productsError.getIn([index, err])
)

now I would like err to be one of the keys I have in my interface

export interface IProductError {
  isPriceError: boolean;
  isAmountError: boolean;
  isDescriptionError: boolean;
}

is there any way to annotate that instead of string?

Upvotes: 0

Views: 30

Answers (1)

Jörg W Mittag
Jörg W Mittag

Reputation: 369468

The type operator you are looking for is literally named after your problem: you want the type to be a "key of" IProductError, and the operator is named keyof.

export const getCreateProductsError = (index: number, err: keyof IProductError) =>
  createSelector(
    getCreateFeatureState,
    state => state.productsError.getIn([index, err])
  )

keyof produces a union of literal types corresponding to all the keys, i.e. keyof IProductError is equivalent to "isPriceError" | "isAmountError" | "isDescriptionError".

Upvotes: 1

Related Questions