Sub topic 6
Weak Type Detection
Prerequisites
Assume you know basic TypeScript interfaces, optional properties, object types, and assignment errors. This chapter focuses on one special rule: how TypeScript checks assignments to weak types.
A weak type is an object type with only optional properties and no required properties or index signature. For example:
interface Options {
color?: string;
width?: number;
}An Options value may contain color, width, both, or neither. Because it accepts almost any object shape, TypeScript adds a safeguard. The source value must share at least one property with the weak target type.
const input = { colour: "red" };
const options: Options = input;
// Error: no properties in common with type 'Options'The spelling mistake is important. colour is not color, so the source and target have no properties in common. TypeScript rejects the assignment even though all properties in Options are optional.
How the check works
Think of the assignment as a question:
Can the source value be safely used as the target type?For a weak target, TypeScript first looks for a shared property. If it finds one, normal structural assignability continues.
const input = {
color: "red",
fontSize: 16,
};
const options: Options = input; // OKinput has the color property from Options. Its additional fontSize property is allowed because input is an existing variable.
A fresh object literal is checked more strictly:
const options: Options = {
color: "red",
fontSize: 16,
};
// Error: 'fontSize' does not exist in type 'Options'This error is an excess property check. It happens because the value is written directly in the assignment. Weak type detection explains the no-common-properties error; excess property checking explains the extra-property error.
You can separate the steps by storing the object first:
const input = {
color: "red",
fontSize: 16,
};
const options: Options = input; // OKThis does not make misspelled properties safe. An object with only colour still fails because it has no shared property.
Avoiding accidental weak types
If an option must be present, make it required:
interface RequiredOptions {
color: string;
width?: number;
}Now an object needs color, so it is no longer a weak type. An index signature also changes the behavior when the type intentionally supports arbitrary keys:
interface Metadata {
[key: string]: string | number;
color?: string;
}Use these designs only when they describe the real data. Weak type detection is useful because it catches likely spelling mistakes without abandoning structural typing.
Exercise
Why does const value = { colour: "red" }; const x: Options = value; fail when every property in Options is optional?
Show answer
Options is a weak type, and value shares no property name with it. colour does not match color.