简体   繁体   中英

write an object with keys and array typescript

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'],
};

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' 'en' | 'de' for indexing to work.

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'],
};

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