'How to assign values of an object in constructor to all properties of class?

I'm trying to easily assign all of the properties in an object in a constructor to all of the properties in a class

type tCustomUpload = {
    name : string,
    relationship : string,
    priority : number,
    id : number
}
class CustomUpload {
    name : string;
    relationship : string;
    priority : number;
    id : number;
    constructor (payload : tCustomUpload) {
        Object.assign(this, payload);
    }
}

I tried the answer at How to assign values to all properties of class in TypeScript? but there are 2 issues with that answer

  1. the interface has optional properties, whereas I want them required
  2. typescript actually flags that answer as having errors, along the lines of Property 'x' has no initializer and is not definitely assigned in the constructor.

ts playground



Solution 1:[1]

TypeScript doesn't really iterate over properties to assign with Object.assign the way you're wanting it to. It's less type-safe, but you can assert that the properties exist with !:.

type tCustomUpload = {
    name: string,
    relationship: string,
    priority: number,
    id: number
}
class CustomUpload {
    name!: string;
    relationship!: string;
    priority!: number;
    id!: number;
    constructor(payload: tCustomUpload) {
        Object.assign(this, payload);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance