TypeScript Tutorial #7 - Delayed Initialization

Veröffentlicht am: 22 Juni 2021
auf dem Kanal: Free Tutorial Wale
40
0

#Delayed #Initialization

Quite commonly in JavaScript code bases, you would initialize object literals in the following manner:

let foo = {};
foo.bar = 123;
foo.bas = "Hello World";

As soon as you move the code to TypeScript you will start to get Errors like the following:

let foo = {};
foo.bar = 123; // Error: Property 'bar' does not exist on type '{}'
foo.bas = "Hello World"; // Error: Property 'bas' does not exist on type '{}'
This is because from the state let foo = {}, TypeScript infers the type of foo (left-hand side of initializing assignment) to be the type of the right-hand side {} (i.e. an object with no properties). So, it error if you try to assign to a property it doesn't know about.

Of course using the any assertion can be very bad as it sort of defeats the safety of TypeScript. The middle ground fix is to create an interface to ensure
1. Good Docs
2. Safe assignment

This is shown below:

interface Foo {
bar: number
bas: string
}

let foo = {} as Foo;
foo.bar = 123;
foo.bas = "Hello World";

Here is a quick example that shows the fact that using the interface can save you:
interface Foo {
bar: number
bas: string
}

let foo = {} as Foo;
foo.bar = 123;
foo.bas = "Hello World";

// later in the codebase:
foo.bar = 'Hello Stranger'; // Error: You probably misspelled `bas` as `bar`, cannot assign string to number


Auf dieser Seite können Sie das Online-Video TypeScript Tutorial #7 - Delayed Initialization mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer Free Tutorial Wale 22 Juni 2021 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 40 Mal angesehen und es wurde von 0 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!