B
B
BonBon Slick2020-05-31 17:24:56
typescript
BonBon Slick, 2020-05-31 17:24:56

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;
}

Difference?
Which approach, when and why to use?

Since I checked such code
@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
    }
};


As you can see from the code, the parameter is undefined everywhere, which can lead to errors if all properties are declared like this, and they are declared for Vuex TS modules - then the meaning of TS typing disappears. Which raises the question for me j of the feasibility of using TS for Vue

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twoone, 2020-05-31
@BonBonSlick

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 question

Ask a Question

731 491 924 answers to any question