Search code examples
typescriptclass-transformer

Why there are no initializers or class constructor in class-transofrmer demo?


import { Expose, plainToClass } from 'class-transformer';

class User {
  @Expose() id: number;
  @Expose() firstName: string;
  @Expose() lastName: string;
}

const fromPlainUser = {
  unkownProp: 'hello there',
  firstName: 'Umed',
  lastName: 'Khudoiberdiev',
};

This is the demo from class-transformer's document. Here is my question: isn't User a invalid Typescript Class, since It doesn't have any initializers for properties or constructor? In fact, after I copyed this demo into IDE, I immediately got the ts(2564): Property 'id' has no initializer and is not definitely assigned in the constructor error


Solution

  • "isn't User a invalid Typescript Class"

    It's invalid if

    {
        ...
        "compilerOptions": {
            ...
            "strict": true
            ...
        }
        ...
    }
    

    and valid if

    {
        ...
        "compilerOptions": {
            ...
            "strict": false
            ...
        }
        ...
    }
    

    in tsconfig.json.

    --strict

    Enable all strict type checking options. Enabling --strict enables --noImplicitAny, --noImplicitThis, --alwaysStrict, --strictBindCallApply, --strictNullChecks, --strictFunctionTypes and --strictPropertyInitialization.

    [Compiler Options]

    It's actually strictNullChecks.