All posts by admin

Dart nullable, if-null, and assertion operator

Not null-able

If we annotate a type to be say, int, it means it can only be an integer. It cannot be null.

We can’t add two numbers if one of them is null:

Nullable (?)

If you want that int to be null, use the question mark to denote that.

With nullable, we get Compile Time Error.
This makes us write safer programs.

Assertion Operator (!)

If you’re sure that a nullable variable will ALWAYS have non-nullable values,
it’s safe to assign it to a non-nullable variable with the ! operator.

However, if you’re wrong, you’ll get a runtime error!

if-null operator (??)

In the example, x is -1, and thus maybeValue will be null;

Usually, we’d write it like this:

Now, we can use if-null operator like so:

Null Safety with type safety

So if x is -1, then maybeValue is left with null.
That’s not very good for future usage and printing.

So we can use a Type safety where if maybeValue is null, then we assign it to a default number.
Its a shorthand for if-null

Conditional Access Operator

Say we declare an array, and its of type String?.

in order to fix this, we use conditional access operator:

Mac setup for flutter

ref –

  • https://trevorsullivan.net/wp-content/uploads/2015/11/Trevor-Sullivan-VI-Shortcuts.pdf
  • https://stackoverflow.com/questions/58387606/flutter-app-running-error-dart-can-not-be-opened-developer-can-not-be-verified

Download flutter and unzip it into say, your home directory /Users/username.

Still in your home directory, type:

ls -la

You should see a whole list of files.

Look for a .zshenv or a .zshrc file:


-rw-r–r– 1 rtsao staff 91 Mar 23 16:10 .zshenv

If it doesn’t exist, just create one:

touch .zshenv

If you do have it just edit it:

vi .zshenv

Then in that file, put flutter’s bin directory in PATH:

then type:
flutter doctor

and follow the flutter URLs to download the needed packages:

  • Install xCode
  • Install Android

As flutter is downloading and executing, sometimes you’ll need to allow security to let it run:

Go to System Preferences > Security and click ‘Open Anyways’ for some of the packages that is trying to install.

There is a special situation where gen_snapshot will repeatedly get denied because the system can’t verify the developer.

You can allow your mac/apps downloaded from anywhere with this command:

sudo spctl –master-disable

As you download apps and allow access to installations, eventually everything will be a success:


Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.3, on macOS 11.1 20C69 darwin-x64, locale en-CN)
[✓] Android toolchain – develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode – develop for iOS and macOS
[✓] Chrome – develop for the web
[✓] Android Studio (version 4.1)
[✓] IntelliJ IDEA Community Edition (version 2020.3.2)
[✓] VS Code (version 1.54.2)
[✓] Connected device (1 available)

• No issues found!

Fields with Inheritance in typescript

If we were to construct our Car, we need to make sure it call the parent class’s constructor. We do this by using super, and passing in whatever required parameters is required. In our case, it is color: string.

We then declare new property wheels for Car.

Lastly, make sure we put in the required constructor params for Car when we instantiate it.

Classes in typescript

If we want Car to have different drive, simply redefine:

Modifiers

public, private, protected – Restrict access

public – can be called any where, any time
private: can be only called by other methods in THIS class.
protected – called by other methods in THIS class, or by other methods in child classes.

by default, it’s public.

If we’re ever over-riding an interface, we cannot change modifier:

If its protected, we can can access in child class.

shortcut

Also note that if we change it to private, then child classes can’t access it anymore.

In order to be made accessible in child class, we can change it back to public or protected.

Interfaces in typescript

Interface + Classes = How we get strong code reuse

Long Type Annotation

Given an object like so:

Say we want to implement a function that takes in such a type. We say, this parameter is called vehicle, and it takes in an object with property name of type string, year of type number, and whether it is broken…which is of type boolean.

Boy, this function annotation is really really long and tiring on the eyes

How to fix this long Annotation?

Creating an interface is like we are creating a type.

will tell us that we need a type like this:

now we can do this:

which is much easier on the eyes and fingers.

By definition, typescript gives us compile time checking. If we change true to 1 in oldCivic, we’ll get compile time checking for oldCivic, that it does not conform to the interface.

Functions around Interfaces

Is it important that Vehicles MUST have these properties? No, as long as Vehicle interface is a subset of what is provided in oldCivic, then we are okay.

In other words, as long as what we declared are included in the interface, then it is ok.

That is the ONLY QUESTION that is asked when we’re trying to check if the passed in object has the properties of the interface.

Let’s change the name Vehicle to Reportable. It is much more descriptive.
And change the function name.

Code Reuse with Interfaces

Notice we both have summary function that returns a string. They are both considered to be ‘Reportable’ types. So they can both be used in the parameter.

We can use a single interface to describe very different objects.

Arrays in Typescript

Typed Arrays – Arrays where each element is some consistent type of value.

Multiple Types in Arrays

When to use Arrays?

When we want to represent a collection of records which some arbitrary sort order.
of same type.

https://stackoverflow.com/questions/49047886/whats-difference-between-array-and-tuple/49047969

Tuple vs Arrays

Tuple – A tuple is a grouping of unnamed, ordered values. Each value in a tuple does not need to be the same type.

Array An array is mutable collection. They are very efficient to create, but must always be a single type.

We have a literal object like this:

type alias

But Why Tuples!?

Here’s why we don’t really use it too much.

It does not describe what those numbers mean. It is not descriptive.

Let’s use object instead. It is much more descriptive because we are forced to put in a key.

Typescript add Annotation onto Functions

Type annotations for functions – Code we add to tell Typescript what type of arguments a function will receive and what type of values it will return.

Type inference for functions – TS tries to figure out what type of value a function will return.

Alternate forms of syntax

Annotate a by providing type number
Annotate b by providing type number
Annotate the return value by providing type number

if no return value, we can specify void

TypeScript introduced a new type never, which indicates the values that will never occur.

Difference between never and void

ref – https://www.tutorialsteacher.com/typescript/typescript-never

The void type can have undefined or null as a value where as never cannot have any value.

A function that has return type void, and no return value, actually defaults to return undefined.

If you you use never type, then sayHi will give a compile time error, as void is not assignable to never.

Destructuring with Annotation

In order to do parameter destructuring, we do this:

Annotation with Objects

Typescript Inference

Typescript Inference

variable declaration: const color
variable initialization: ‘red’

If declaration and initialization are on the same line, Typescript will figure out the type of ‘color’ for us.

But when are we going to add in these type Annotations?

If typescript can figure it out, why would we want to do it yourselves?

Try to use Type Inference.

But there are THREE scenarios where we rely on Type Annotations to help Typescript out.

Scenario 1 – ‘Any’ type

Whenever a function return the any type.

JSON.parse() –> ‘false’ –> boolean
JSON.parse() –> ‘4’ –> number
JSON.parse() –> ‘{“value”, 5}’ –> {value:number}

Can’t predict what we get in return.

So as a shortcut, typescript uses ‘Any’ type.
We have no idea what type gets returned.

type Any – means TS has no idea what this is – can’t check for correct property references

Avoid variables with ‘any’ at all costs.

The reason why is because say we have declare speed to be string:

if we then go

TS will let us know that property abcdef does not exist. Because TS knows that speed is a string.
But with Any, TS doesn’t know, and won’t be able to do this check for you.

Scenerio 2 – How to use Use Type Annotation to Fix the ‘Any’ Type

We can add type annotation for object.

Say we’re expecting an object where there’s a x and y property of type number.

Now if we mouse over coordinates, or try to access a weird random property, we’ll get proper feedback or error.

Delayed Initialization

Another way to add type annotation manually…

Scenario 3 – variable shows Type cannot be Inferred Correctly

what we could do:

webpack and typescript

Webpack is a tool that allows us to bundle our code. Transform our typescript code into javascript, then emit 1 javascript bundle file.

Webpack-dev-server is a development server.

Set up a webpack project

go to tsconfig file.

“target”: “es6”
“module”:”2016″

touch webpack.config.js

webpack will automatically look for this file.