0

If I have an interface like this:

interface OptionsType {
  name: string;
}

Then when I try to use that interface with a property that is not defined, I get Type '{ value: string; disabled: boolean; }' is not assignable to type 'OptionsType'.   Object literal may only specify known properties, and 'disabled' does not exist in type 'OptionsType'.

This is good, I want this error to occur when I make this mistake. My problem comes from when I use this in Array.map, it does not give me the error. How can I make it so that my usage of Array.map is properly typed?

Errors properly:

const optionsArr: OptionsType[] = [
  {
    value: 'hello',
    disabled: false, // error
  },
];

const options: OptionsType = {
  value: 'thing',
  disabled: true, // error
};

Does not error:

const optionsArrMapped: OptionsType[] = [1, 2].map(num => ({
  value: 'idk',
  disabled: true,
}));

// As an example, using `as` prevents the error from happening. I'm not less concerned about this case.
const optionsAs: OptionsType = {
  value: 'thing',
  disabled: true,
} as OptionsType;

2 Answers 2

1

You can specify a return type for map function using generics:

const optionsArrMapped: OptionsType[] = [1, 2].map<OptionsType>(num => ({
  value: 'idk',
  disabled: true,
}));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, that looked like it was going to work. It does make sure that I'm returning all the required properties. But I'm still not seeing any errors when I add random properties to the returned object.
What version of TypeScript do you use?. Could you show your tsconfig.json file? I've checked with version 2.7. VSCode shows me errors when I add random properties or not all required properties.
Yes, I've checked. It doesn't show error me too. I'll have a look
TypeScript 3.8.3 is on this project, here's the tsconfig without our paths. { "compilerOptions": { "module": "amd", "moduleResolution": "node", "sourceMap": true, "target": "es2017", "jsx": "react", "experimentalDecorators": true, "allowSyntheticDefaultImports": true, "resolveJsonModule": true, }
It seems it still does not error in TypeScript 5.2.2. TS playground
1

The correct way to resolve this is to explicitly type the return value of Array.map():

const optionsArrMapped: OptionsType[] = [1, 2].map((num): OptionsType => ({
  value: 'idk',
  disabled: true,
}));

TS Playground

Comments

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.