I have got error TS2322: Type 'string' is not assignable to type 'never'.
in result[key] = forms.${key};
and don't understand how i can fix it. (without prefix everything is ok).
Why typescript considers result[key]
as never?
export const InitialState = {
login: {
login: '',
password: '',
accept_terms: false,
},
forgot: {
login: '',
password: '',
},
};
type FormsKey = keyof typeof InitialState;
type FormsMap = {
[K in FormsKey]: `forms.${K}`
};
const keys = Object.keys(InitialState) as FormsKey[];
const forms: FormsMap = keys.reduce<FormsMap>((result, key) => {
result[key] = `forms.${key}`;
return result;
}, {} as FormsMap);
export default forms;
CodePudding user response:
Because of const forms: FormsMap = keys.reduce<FormsMap>((result, key) => {
typescript undesturd result[key] as a undefined possibility, e.g. if you find an unknow key , thats return never, if you have a defined explicit keys, you should create a type or enum for match for this key. Otherise I suggest you avoid set value in array, insteread you use an Map type for this.
CodePudding user response:
export const InitialState = {
login: {
login: '',
password: '',
accept_terms: false,
},
forgot: {
login: '',
password: '',
},
}
type FormsMap<T> = {
[K in keyof T]: K extends string ? `forms.${K}` : never
}
const getForms = <T>(state: T) => {
const result: Record<string, any> = {}
Object.entries(state).forEach(([key]) => {
result[key] = `forms.${key}`
})
return result as FormsMap<T>
}
const forms = getForms(InitialState)
// type forms = {
// forgot: "forms.forgot"
// login: "forms.login"
// }
export default forms