V
V
Vladimir Mirka2019-01-31 11:38:08
JavaScript
Vladimir Mirka, 2019-01-31 11:38:08

How to change type in TypeScript?

In short, I get a data object with one type. You need to return the same object, but with changed fields. When you try to change the fields of the vehicle swears. Using any is not an option.

UserEntity {
    id: number;
    name: string;
    email: string;
    profile: ProfileEntity[];
    contact: ContactEntity;
}

const a = UserEntity;
We get an error here:
a.profile = [1,2,3];
a.contact = 159;

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Proskurin, 2019-01-31
@Vlad_IT

You can use the | operator, Union Types. Example

class UserEntity {
    public name: number | string;
}

here name can be either a number or a string.
Read more here https://www.typescriptlang.org/docs/handbook/advan...

M
msdosx86, 2019-01-31
@msdosx86

a.profile = [1,2,3] as any;
a.contact = 159 as any;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question