I have created the following interface, which I want to use to cap a property, which I then load with the response from the Strava api.
Interface
export interface Athlete {
state: string;
code: string;
scope: string;
id: number;
username: string;
resource_state: number;
firstname: string;
lastname: string;
bio?: any;
city: string;
country: string;
sex: string;
premium: boolean;
summit: boolean;
created_at: Date;
updated_at: Date;
badge_type_id: number;
weight: number;
profile_medium: string;
profile: string;
friend?: any;
follower?: any;
}
When trying to use it in the component
export class UserComponent implements OnInit {
athlete: Athlete;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _oauth: OauthService
) {}
ngOnInit(): void {
this._route.queryParams.subscribe((params) =>
this._oauth.refreshToken(params.code).subscribe((resp) => {
this.athlete = resp.athlete;
})
);
}
}
In the line athlete: Athlete;
it throws me the error
La propiedad "athlete" no tiene inicializador y no está asignada de forma definitiva en el constructor.
I don't understand, I've consulted a lot of documentation and I haven't read any that need to have a constructor, and I also believe that there can't be an interface, but rather a class that implements said interface should be assembled; I don't know if it would be the right thing for what I'm looking for, which is to pull the data from the variables I work with.
That
strict
's because typescript mode is on. You can document yourself about the modestrict
HereThe configuration is in the project file
tsconfig.js
, similar to this:Back to your case. Instead of creating a class that implements the interface, you can add a
!
to the name of the variable, with that you tell the compiler not to show the error because you ensure that that variable will be initialized, leaving the declaration like this:In case I can help someone, this is how I solved it.
If you see a more optimal solution, I would love for you to comment on it.
Let's get to the point, on the one hand I keep the interface that I already had
On the other I have created a class, in which I implement the interface and in the constructor I initialize all the properties
And so now I can use them to type and to declare new properties, you can even type the subscription responses (as seen with the Welcome)
From the TS 2.7 documentation ( Link )
If you want to keep the interface instead of the class that I see you have changed, it would suffice to initialize it as requested in the constructor, even if you initialize it to null if you want to do the assignment later without expressly indicating the promise to declare it with the ! (as you have already been told).
Hope this can help you!