TypeScript Reference ยท Error Codes Worth Knowing
TypeScript error TS2741: Property is missing in type
Reference for TypeScript error TS2741: a required property is missing from an object. See causes with interfaces and classes, and fix it with optional fields or Partial.
TS2741 is a specialized form of TS2322. The source type has everything compatible except that one required property is absent. The message names it: Property 'age' is missing in type '{ name: string; }' but required in type 'User'.
When several properties are missing, TypeScript reports TS2739 (Type 'X' is missing the following properties from type 'Y': a, b) or, past a handful, TS2740 with a count.
interface User { name: string; age: number } const u: User = { name: "Ann" }; // TS2741
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
| Fix | When |
|---|---|
| Add the property | The value really should have it. |
Make it optional: age?: number |
It is legitimately absent in some cases; readers must then handle undefined. |
Partial<T> for the input |
The object is a set of overrides or an update patch. |
Pick<T, K> or Omit<T, K> |
The value is a subset of the full type, e.g. a creation payload without id. |
| Separate types | Input, stored and output shapes differ; give each a name. |
| Provide a default via spread | { ...defaults, ...input }. |
Class case: a class instance is missing a member that an interface requires; the same error appears, and implements makes it show on the class name (TS2420).
Usage notes
- Read the target type. The second type in the message is what the compiler wants; the first is what you supplied.
- Optional does not mean
undefinedis allowed everywhere. UnderexactOptionalPropertyTypes,age?: numberaccepts a missing key but not an explicitundefined. - Excess vs. missing. Misspelled keys in a literal give two errors: an unknown property (TS2353) and a missing one. Fixing the spelling fixes both.
- Nested objects. Only the first failing level is shown; keep reading the indented lines.
- Do not cast.
{} as Settingscompiles and produces an object that breaks later whenfontSizeisundefined. - Builders and factories can produce complete objects so partially built data never has the full type.
- Arrays of objects: the error is reported on the first element that fails.
Related
- TS2322
- TS2353
- Partial
- Tutorial: Interfaces, Utility types