helloword.ts:6:7 - error TS2345: Argument of type '20' is not assignable to parameter of type 'string'.
6 hello(20) ~~ Found 1 error.
2 Data Type
2-1 Data types in Javascript
There are 7 primitive data types: - Boolean - Null - Undefined - Number - BigInt (ES6) - String - Symbol (ES6) And Object
2-2 Basic Data Types
Some basic data types:
letisDone: boolean = false
letage: number = 20 letbinNumber: number = 0b1111
letfirstN: string = "Isaac" letmsg: string = `Hello ${firstN}, age is ${age}`
letudf: undefined = undefined letn: null = null ``` note `undefine` and `null` are sub-type for `number`, `string` and `boolean`, we can define a `number` type `undefined` Below is valid: ```typescript letmyNum: number = undefined
2-3 any Type and uniTypes
For unknown types, we can use any
Be cautious on any
letnotSure: any = 4 notSure = "maybe it is a string" notSure = true
Unitypes: could be a combined types
letnumberOrString: number | string = 234 numberOrString = "a string"
// below will be an error // numberOrString = true
console.log(cat.run()); ``` ## 2-8 Class Two - There are three types of attributes - public - private - protected - public: we can change the attribute and ```typescript classAnimal { publicname: string; constructor(name:string) { this.name = name } run(){ return`${this.name} is running` } }
const python = newAnimal("three")
console.log(python.run()); console.log(python.name) python.name = "3.8" console.log(python.name) ``` - private: for some attributes or methods inaccessible from the outsiders, including child class ```typescript classAnimal { privatename: string; constructor(name:string) { this.name = name } run(){ return`${this.name} is running` } }
protected: child class can access the protected attributes or methods
classAnimal { protectedname: string; constructor(name:string) { this.name = name } run(){ return`${this.name} is running` } }
readonly: can only read but not edit
classAnimal { readonlyname: string; constructor(name:string) { this.name = name } run(){ return`${this.name} is running` } }
static attributes and methods: can be accessed without instantiation
classAnimal2 { readonlyname: string; staticcategories: string[] = ["mammal", "bird", "others"] staticisAnimal(a) { return a instanceofAnimal2 } constructor(name:string) { this.name = name } run(){ return`${this.name} is running` } }