M.Dietz
M.Dietz

Reputation: 998

TypeScript, const/enums type

I have the following const/enum:

export const LENGTH_LIMIT = {
  MAX_INPUT_CUSTOMER_FORM: '500',
  MAX_INPUT_EMPLOYEE_FORM: '500'
};

I would like to give it a type. But can i give LENGTH_LIMIT a type besides any? Or is any the only thing which would work here?

Upvotes: 0

Views: 487

Answers (4)

Aziz.G
Aziz.G

Reputation: 3721

you can create an interface for example:

interface LengthLimit {
    [name: string || any]: string
}

then:

export const LENGTH_LIMIT : LengthLimit = {
  MAX_INPUT_CUSTOMER_FORM: '500',
  MAX_INPUT_EMPLOYEE_FORM: '500'
};

Upvotes: 0

ontananza
ontananza

Reputation: 392

If you want declare as enum:

export enum LENGTH_LIMIT {
  MAX_INPUT_CUSTOMER_FORM = '500',
  MAX_INPUT_EMPLOYEE_FORM = '500',
}

If you want to use a variable of type LENGTH_LIMIT in HTML template you must assign it:

LengthLimitOptions: any = LENGTH_LIMIT;

And in HTML use as:

<span>{{LengthLimitOptions.MAX_INPUT_EMPLOYEE_FORM}}</span>

Upvotes: 0

davidlj95
davidlj95

Reputation: 1598

You could use TypeScript enums for this. Then, the type would be the enum itself:

export enum LENGTH_LIMIT {
  MAX_INPUT_CUSTOMER_FORM = '500',
  MAX_INPUT_EMPLOYEE_FORM = '500',
}

And to use it:

interface CustomerForm {
    InputLimit: LENGTH_LIMIT
}

Upvotes: 0

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10137

1) That's an object, not an enum

2) Why do you want to give constants a type? Typescript already infers them for you. It infers this:

interface LenghtLimit {
    MAX_INPUT_CUSTOMER_FORM: string,
    MAX_INPUT_EMPLOYEE_FORM: string
}

Upvotes: 3

Related Questions