Being a dumbass is a human right — Part 2
People at my workplace has a dislike for TypeScript. I dont really see the problem, can’t you just put it to any?
What is Typescript
Typescript is a superset of javascript, meaning that it has everything that javascript has. However, Javascript allows us to assign any value to any variable. Usually this leads to bugs and reads horribly. Typescript implements the type interface, meaning that at any point in our program, Typescript expects the data type of the variable to be consistent.
Any
Aka. The only thing I care about.
Any is a type that can be assigned a value to indicate that it does not have a type. An any-type variable is usually a variable that was assigned without an initial value. Basically, anything goes:
let onOrOff;
onOrOff = 1;
onOrOff = false;
I realise now, after looking at it, that you could basically just write Javascript if you just use any. So what is even the point (of anything).
Type annotation/type declaration
Variables can have type annotations right after their names. It’s on this format:
let mustBeAString : string;
mustBeAString = ‘Catdog’;
This way, we can assign a type to a variable without it being initialised with a value.
The tsconfig.json-file
All I know of this is that whenever I start Docker, the tsconfig-file is missing. So surely it can’t be important.
So Typescript has a lot of rules. Rules that are not always necessary, and I don’t think the seniors in my team care for. Insert the tsconfig.json-file (literally). Here you can customize the rules you want the ts-compiler to enforce.
Where does the tsconfig.json live?
It’s always in the root of your project.
What does it look like?
{
“compilerOptions”:
{
“target”: “es2017”,
“module”: “commonjs”,
“strictNullChecks”: true
},
“include”: [“**/*.ts”]
}
I don’t know what that means. Do you? Perhaps you do, then why are you still reading this article, you clearly know what you’re doing. Oh? It’s because the article is so neatly written. Thank you. I appreciate it. Oh that’s not what you said? You told me to… To what? Stick my hand in a shredder? Have some therapy.
Functions
Functions
Just like variables, functions can have type declarations as well. And of course, if it does not have a type, it’s any.
function greet(name: string)
Optional variables
Seeing as Typescript throws errors left and right, we (quite often) don’t want that, so we make it optional to have arguments in functions. This is done by adding a question mark.
function greet(name?: string) {
console.log(`Hello, ${name|| ‘Anonymous’}!`);
}
greet(); // Prints: Hello, Anonymous!
Default parameters
You don’t always need the optional variables. Sometimes you know what should be the standard, and thats when you should use default parameters. It reads a lot better too. For example:
function greet(name = ‘Anonymous’)
Now you know TypeScript. Fantastic.
Anyways, we’re switching to Kotlin now.