0

I am writing the following in typescript and see the following error

const WEEKDAYS_SHORT = {
    en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};

<StyledDayPicker weekdaysShort={WEEKDAYS_SHORT[language]} />

Type 'string[]' is not assignable to type '[string, string, string, string, string, string, string]'. Property '0' is missing in type 'string[]'. [2322]

I have tried the following which is giving me an error.

const WEEKDAYS_SHORT: string[] = {
    en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};
3

2 Answers 2

1

weekdaysShort expects a string tuple of length 7. By default typescript infers arrays of fir array literals. The simple solution is to usa an extra function to help inference along:

const stringTuple = <T extends string[]>(...a: T) => a;

const WEEKDAYS_SHORT = {
    en: stringTuple('S', 'M', 'T', 'W', 'T', 'F', 'S'),
    de: stringTuple('S', 'M', 'D', 'M', 'D', 'F', 'S')
};

Or you can use a type assertion:

type Tuple7 = [string,string,string,string,string,string,string]
const WEEKDAYS_SHORT = {
    en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'] as Tuple7,
    de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'] as Tuple7,
};

Or in typescript 3.4 (unreleased at this time) you can assert as const to make the compiler infer a readonly tuple:

const WEEKDAYS_SHORT = {
    en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
} as const;

Also depending on your compiler setting, and the language should be 'en' | 'de' for indexing to work.

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

3 Comments

any idea for this one 'Typescript King' - stackoverflow.com/questions/54575523/…
@peterflanagan :)) I can have a look
I think I have figured it out/the answer there answers it. It is a react issue not a ts one
0

Your variable should be defined as such:

const WEEKDAYS_SHORT: { [prop: string]: string[] } = {
    en: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
    de: ['S', 'M', 'D', 'M', 'D', 'F', 'S'],
};

1 Comment

it is still complaining . Also is prop a keyword, or can I use anything there. As said below it is because it is expecting a string tuple of length 7. I didn't know this

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.