0

this might be a really simple question after all. But I didn't find a solution yet.

I have a dynamic object defined with a signature index. Usually, all properties should be of type string. But there are a few exception. width for example should always be of type number. Yet when I add it to my interface I get the error

error TS2411: Property 'width' of type 'number' is not assignable to string index type 'string'.

This would be my interface:

interface DynamicStyleObject {
  [ key : string ] : string;
  width : number;
}

1 Answer 1

0

If sometimes your property can be a number, you can make the index type string | number, so it accepts either number or string properties.

interface DynamicStyleObject {
  [ key : string ] : string|number;
  width : number;
}

Ref.: Discriminated unions, also known as tagged unions or algebraic data types pattern

Sign up to request clarification or add additional context in comments.

4 Comments

So it is not possible to have a default type of string and only for width having number?
Oh ok, I just found that I can "extend" it this way, saying that in general both string and number are allowed but for width only number is valid.
@lumio yes that's what I meant, sorry I forgot to add the width property (I've updated though). The point is, string|number will allow properties of type string and number, this way you can specify properties strict to one of those types like width: number and also display: string.
Yea I forgot the width myself in the beginning. No worries. Thanks for the simple answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.