Answer the question
In order to leave comments, you need to log in
Definite assignment assertion modifier VS undefined?
Docs
It is said what can be done, but without describing the difference.
class C {
foo!: number;
foo: number | undefined;
}
@Module({namespaced: true, name: 'test'})
export default class User extends VuexModule {
public name!: string;
public get nameUpperCase(): string {
console.log(this.name) // undefined
return this.name
}
@Template
@Component<LayoutDefault>
export default class LayoutDefault extends Vue {
@user.Getter
public nameUpperCase!: string // undefined
public mounted(): void {
console.log(this.nameUpperCase); // undefined
}
};
Answer the question
In order to leave comments, you need to log in
The difference is that the second option allows undefined, which the compiler will try to prevent. The first way makes a run-time error that you create bypassing the compiler.
And it seems to me that this is normal, because ts, due to its static typing, takes upon itself the obligation to prevent the compilation of uninitialized fields. And he does it perfectly! But by indicating an exclamation mark in the ad, you shift this obligation onto yourself. It turns out that if there is an error, it is entirely your fault. ts has nothing to do with it. If you take the helm and know the dangerous turns, then it is you who must prevent a disaster, not the autopilot. That is, you must change the type of the getter to optional.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question