Presented by Atlassian
When it comes to building software, sometimes you go in already having won or lost the fight.
function manyString(repeat, str) {
let outString = '';
for (let i = 0; i < repeat; i++) {
outString += str;
}
return outString;
}
console.log(manyString('hello ', 5));
function sum(a: number, b: number) {
return a + b;
}
console.log(sum(1, 2));
function nicksBug(
param1: string,
param2: number,
param3: number,
param4: number,
param5: string,
param6: string
) {
// ...
}
const bad = nicksBug('hello', 1, 44, 20, 58, 421, 'world')
npm install --save-dev typescript ts-node
node_modules/.bin/ts-node 3.3_mycode.ts
node_modules/.bin/tsc --noImplicitAny 3.3_mycode.ts
node_modules/.bin/tsc 3.3_mycode.ts
Types are added to programs typically by putting the type name after a colon. We've seen that in our first example.
Typescript doesn't require you to put types on everything. It will infer types that it can, but sometimes it's unable to.
function hello(name: string) {
console.log(name);
}
function hello(name) {
// should be hello(name: string)
console.log(name);
}
const name = 'Yuchao'
TypeScript can't figure this out
TypeScript can figure this out
function hello(name: string): string {
return `Hello ${name}!`;
}
function printIfReady(ready: boolean | number) {
if (ready === true || (ready && ready !== 0)) {
console.log(`Ready! ${ready}`);
}
}
printIfReady(1);
printIfReady(2);
printIfReady(0);
printIfReady(true);
printIfReady(false);
function create10List(item: string | number) {
const arr: Array<string | number> = [];
for (let i = 0; i < 10; i++) {
arr.push(item);
}
return arr;
}
type ListItem = string | number;
function create10List(item: ListItem) {
const arr: ListItem[] = [];
for (let i = 0; i < 10; i++) {
arr.push(item);
}
return arr;
}
// Note:
// end?: number
// = end: number | undefined
function substring(str: string, start: number, end?: number) {
let newString = '';
const modifiedEnd = end || str.length;
// ^ What about end ?? str.length
for (let i = start; i < modifiedEnd; i++) {
newString += str[i];
}
return newString;
}
console.log(substring('hayden', 0, 3));
console.log(substring('hayden', 2));
type Person = {
name: string;
age?: number;
height?: number;
}
const person: Person = {
name: 'Yuchao',
};
person.age = 5;
// @ts-nocheck
function hello(name: any): any {
return `Hello ${name}!`;
}
function substring(str: any, start: any, end: any) {
return null;
}
type Person = any;
const person: Person = {
name: 'Yuchao',
};
any
never
string
number
boolean
Custom objects/types
More on this in COMP2511, and even more in COMP3161