Skip to main content

no-unsafe-class-instance-assignment

Disallow assigning non-instance values to class instance typed locations.

💭

This rule requires type information to run, which comes with performance tradeoffs.

In TypeScript, a class declared with the class keyword whose members are all public can be used as a type for any value with the same shape. That means an object literal or any other value with a matching shape can be used where an instance of the class is expected - without ever calling the class's constructor.

This rule reports values that aren't created by a class's constructor but are used where an instance of the class is expected: in variable declarations, assignments, function arguments, return values, as assertions, and so on. That includes values the class only appears inside of, such as a Promise of a plain object assigned to a Promise<Point>.

eslint.config.mjs
export default defineConfig({
rules: {
"@typescript-eslint/no-unsafe-class-instance-assignment": "error"
}
});

Try this rule in the playground ↗

Examples​

class Point {
constructor(
public x: number,
public y: number,
) {}
}

const point: Point = { x: -1, y: -2 };

declare const plain: { x: number; y: number };
const points: Point[] = [plain];
Open in Playground

Limitations​

This rule only checks types declared with the class keyword, including declare class declarations in .d.ts files. Types modeled as an interface paired with a constructor type, such as interface Foo {} alongside declare var Foo: { new (): Foo }, aren't treated as classes by TypeScript, so this rule doesn't report plain objects assigned to them. That includes most built-in types from TypeScript's lib files, such as Promise, Map, and DOM types like DOMParser:

// Not reported: Promise is declared as an interface, not a class
const promise: Promise<string> = {
then: null! as Promise<string>['then'],
catch: null! as Promise<string>['catch'],
finally: null! as Promise<string>['finally'],
[Symbol.toStringTag]: 'Promise',
};

Options​

This rule is not configurable.

When Not To Use It​

If you use classes as plain shapes, such as data containers whose constructors don't do anything important, you might prefer to declare those shapes as interfaces or type aliases instead. If your project relies on that pattern on purpose, this rule may not be for you.


Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degradations after enabling type checked rules.

Further Reading​

Resources​