Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Keep type information after creating spread copy

I have the problem, that I have a function that gets an object. A field of this object can be null, which I want to handle, and afterwards add a field to this object and return it.

Here you can find a simplified version of it.

The problem that I have is that the assertion that the field is not null is lost after I create the spread clone.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to get around this?

>Solution :

The bar.field is string[] information is kept only in bar.field, not in bar itself

type Type1 = {
    field: string[] | null;
}

type Type2 = {
    name: string;
    field: string[]
}

function foo(bar: Type1): Type2 {
    bar.field ??= [];
    const result = { name: "some Name", ...bar, field: bar.field };
    result.field.push("Some String");
    return result;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading