Sub topic 9
Weak type detection
This chapter explains the check TypeScript runs when the target type has only optional properties. It assumes you know the following:
- Basic TypeScript syntax, including interfaces and type aliases.
- Plain assignability between object types.
- The difference between a fresh object literal and a variable that holds an object.
The gap in plain assignability
Under the structural rule, a source is assignable to a target when it has every required member of the target. If every member of the target is optional, nothing is required. In theory, any object would then be assignable, including one that shares no properties with the target.
interface Options {
color?: string;
width?: number;
}
const unrelated = { name: "report", pages: 12 };Without an extra rule, unrelated would be accepted as an Options. It has no color or width, and the target requires neither. That is almost always a bug, such as a misspelled option name or the wrong object passed to a function. Weak type detection closes this gap.
What counts as a weak type
A weak type is an object type that meets all of these conditions:
- It has at least one property.
- Every property is optional.
- It has no index signatures.
- It has no call or construct signatures.
Options above is weak. The following types are not:
interface HasRequired {
color?: string;
id: number; // one required property makes the type non-weak
}
interface Dictionary {
[key: string]: string | undefined; // index signature
}
interface Empty {} // no properties at allThe rule
When the target is a weak type, the source must share at least one property with it. The shared property must have the same name, and its type must still be compatible. If the source has no property in common, the assignment is an error. This applies to every place assignability is checked: variable assignment, function arguments, return values, and so on.
interface Options {
color?: string;
width?: number;
}
const typo = { colour: "red" };
const a: Options = typo;
// Error: Type '{ colour: string; }' has no properties in common with type 'Options'.
const partial = { width: 10, height: 5 };
const b: Options = partial; // OK: 'width' is shared
const matching = { color: "red", colour: "blue" };
const c: Options = matching; // OK: 'color' is shared, so the extra 'colour' is not flaggedThe last assignment shows the limit of the check. It only asks whether there is any overlap. It does not verify that every property of the source is known to the target. Verifying that is the job of excess property checks, and those run only on fresh object literals.
How it relates to excess property checks
The two checks catch overlapping mistakes but fire in different situations.
| Source | Shares a property with the weak target | Result |
|---|---|---|
| Fresh literal `{ colour: "red" }` | No | Excess property error (reported first) |
| Variable holding `{ colour: "red" }` | No | Weak type error |
| Fresh literal `{ color: "red", colour: "x" }` | Yes | Excess property error on `colour` |
| Variable holding `{ color: "red", colour: "x" }` | Yes | Accepted |
For a fresh literal, the excess property check usually reports the problem before weak type detection gets a chance. Weak type detection matters most once the object has passed through a variable, a function return, or a spread. At that point TypeScript no longer treats the object as fresh.
Where weak types come from in practice
Weak types are common because configuration-style APIs are full of optional properties.
- Option bags for functions, such as
{ timeout?: number; retries?: number }. - Hand-written "all optional" interfaces for partial updates.
- The result of
Partial<T>, which makes every property ofToptional.
interface User {
id: number;
name: string;
}
function update(patch: Partial<User>): void {
console.log(patch);
}
const wrong = { username: "ada" };
update(wrong);
// Error: Type '{ username: string; }' has no properties in common with type 'Partial<User>'.
const right = { name: "ada" };
update(right); // OKWithout weak type detection, update(wrong) would compile and silently do nothing useful. The check turns a likely typo into a compile-time error.
Functions are not exempt
A function has call signatures, so it counts as a source with "properties". If you pass a function where a weak type is expected, it must share a property with that type. A function almost never does, so TypeScript reports the mismatch.
interface Hooks {
onStart?: () => void;
onStop?: () => void;
}
function run(hooks: Hooks): void {
hooks.onStart?.();
hooks.onStop?.();
}
run(() => console.log("start"));
// Error: Type '() => void' has no properties in common with type 'Hooks'.This is a common mistake when an API changes from accepting a callback to accepting an object of callbacks. The fix is to wrap the function in the object shape the API expects:
interface Hooks {
onStart?: () => void;
onStop?: () => void;
}
function run(hooks: Hooks): void {
hooks.onStart?.();
hooks.onStop?.();
}
run({ onStart: () => console.log("start") }); // OKWhat the check does not flag
Several sources pass the check even though they look unrelated to the target.
- Sources with no properties. An empty object, typed as
{}, has nothing to compare, so the check is skipped. A source that is wider, such asobject, is treated the same way. - Sources with at least one common property. As the earlier
matchingexample showed, a single shared name is enough. - Targets that are not weak. A single required property, an index signature, or a call signature on the target turns the check off.
interface Options {
color?: string;
width?: number;
}
const empty = {};
const fromEmpty: Options = empty; // OK: the source has no properties to compare
interface OptionsWithIndex {
color?: string;
[key: string]: unknown; // no longer weak
}
const typo = { colour: "red" };
const loose: OptionsWithIndex = typo; // OK: the index signature accepts any nameThe index signature version compiles, but it also gives up the typo protection. Use it only when the object really accepts arbitrary keys.
Responding to the error
When you hit "has no properties in common", work through the causes in this order.
- Check for a misspelled property. This is the most common cause, and the error message is doing its job. Fix the name.
- Check that you are passing the right value. A function where an object is expected, or an object from a different API, produces the same error.
- Check whether the target should have a required member. If every call must supply something, make that property required. The type stops being weak, and callers get a clearer error that names the missing property.
- Add the property you intend to pass to the target type, if the target is yours to change.
- Use a type assertion only when you know the value is valid and the compiler cannot see it.
interface Options {
color?: string;
width?: number;
}
declare const fromLegacyApi: { legacyTheme: string };
// Only when you have verified at runtime that this is acceptable:
const opts = fromLegacyApi as Options;Be careful with the last option. The assertion removes the protection for that one value, and the compiler cannot warn you if the legacy object really does have the wrong shape.
Edge cases and limits
- The check is on names, not on meaning. A shared property with an incompatible type is still an error, but it is reported as an incompatible property, not as a weak type problem.
- Optionality is read from the declaration. With
exactOptionalPropertyTypesorstrictNullChecksthe property types differ, but the question of whether a type is weak depends only on whether all its properties are optional. - Intersections are checked as a whole. If one part of an intersection has a required property, the combined type is not weak.
- Generic code can hide the problem. If the target is an unconstrained type parameter, no weak type check applies. Once the parameter is instantiated with a weak type, the check applies at the call site.
- It protects only direction source to target. Having properties in common is not symmetric. Checking
Optionsagainstunrelatedfails, but that says nothing about the reverse assignment.
Summary
A weak type has properties but no required ones, no index signature, and no call signatures. When the target is weak, a source that has properties or call signatures must share at least one property name with it. An empty source is still accepted. A required property or an index signature on the target removes the check. For fresh object literals, the excess property error usually appears first. For variables, function results and callbacks, weak type detection is what catches the mistake.
Exercise
Given interface Style { bold?: boolean; italic?: boolean } and const s = { underline: true };, does const x: Style = s; compile? What about const y: Style = { underline: true };? Explain which check fires in each case.
Show answer
Neither compiles. In const x: Style = s;, s is a variable, so no excess property check applies. Style is a weak type (all properties optional) and s shares no property with it, so weak type detection reports "has no properties in common". In const y: Style = { underline: true }; the value is a fresh object literal, so the excess property check reports that underline does not exist in type Style.
Exercise
You have interface Config { port?: number; host?: string } and a function start(config: Config). A teammate calls start(() => {}). Why is this an error, and give two ways to change the code so that the error goes away without using a type assertion.
Show answer
A function has call signatures, so it counts as a source with properties, but it shares no property name with the weak type Config. TypeScript reports that () => void has no properties in common with Config. One fix is to call start({ port: 8080 }), passing an object that shares a property. Another is to make a property required, for example host: string, so Config is no longer weak and the error becomes a missing-property error.
Exercise
Why does const c: Options = { color: "red" } as { color: string; colour: string }; style code, that is a variable holding { color: "red", colour: "blue" }, assign to Options (with color? and width?) without error, even though colour is a typo?
Show answer
Weak type detection only requires at least one property in common, and color is shared. The extra colour is not checked because excess property checks apply only to fresh object literals, and a variable or a cast expression is not fresh. The typo therefore goes unnoticed.