TypeScript is an open source language and is a superset of JS.
- offers additional features to js including static types.
- using types is completely optional
- compiles down to regular js
- can be used for FE js as well as BE with node.js
- includes most features from es6, es7 (classes, arrow function, etc)
- types from 3rd party libs can be added with type definitions
Dynamic vs Static typing
- Dynamically typed languages, the types are associated with run-time values and not named explicitly in your code ex) js, python, php, ruby
- Statically typed languages, you explicitly assign types to variables, function parameters, return values, etc ex) java, c, c++, rust, go
⇒ TypeScript is a static typed language.
In dynamically typed languages all type checks are performed in a runtime, only when your program is executing. So this means you can just assign anything you want to the variable and it will work.
If we take a look at Typescript, it is a statically typed language, so all checks will be performed during compile/build run before we actually execute our program.
Pros and Cons
Pros
- more robust
- easily spot bugs
- predictability
- readability
- popular
Cons
- more code to write
- more to learn
- required compilation
- not true static typing
*** It will shine when you work in a big projects with multiple` developers
Compiling TypeScript
- typeScript uses .ts and .tsx extensions
- tsc(typescript compiler) is used to compile .ts files down to js
- can watch files and report errors at compile time
- many tools include ts compilation by default
- most ides have great support for ts
- the tsconfig.json file is used to configure how typescript works
typescript 파일 실행
*** 에러1
tsc -v : 이 시스템에서 스크립트를 실행할 수 없으므로
**** 에러2
his is not the tsc command you are looking for
⇒ Use npx typescript
, not npx tsc
. The tsc
package on npmjs is not TypeScript.
- npm install -g typescript
- npm install -g npx
- npx typescript index.js
OR
- npm install typescript --save-dev
- npx tsc
js 실행
node 경로
Basic types
let id : number = 5 let company:string = 'Traversy Media' let isPublished:boolean = true let x :any ='Hello' let ids : number[] = [1,2,3,4,5] let arr : any[] = [1, true, 'Hello']
Tuple : key - value
//Tuple let person : [number, string, boolean] = [1, 'Brad', true] //Tuple Array let employee:[number, string][] employee = [ [1,'Brad'], [2,'John'], [3, 'Sue'], ]
Union
let pid : string | number = 22 pid = '22'
Enum
숫자 열거형
enum Direction1 { Up = 1, Down, Left, Right } console.log(Direction1.Up) //1 console.log(Direction1.Down) //2 console.log(Direction1.Left) //3 console.log(Direction1.Right) //4 enum Direction2 { Up = 'UP', Down= 'Down', Left='Left', Right= 'Right', } console.log(Direction2.Up) //'UP' console.log(Direction2.Down) //'Down' console.log(Direction2.Left) //'Left' console.log(Direction2.Right) //'Right'
Objects : 2 ways
//1. type User = { id:number, name:string } const user : User ={ id : 1, name : 'John' } //2. const user : User ={ id:number, name:string } = { id : 1, name : 'John' }
Type Assertions
let cid : any = 1 //We cna do either way let customerId = <number> cid let customerId = cid as number
Functions
function addNum(x:number, y :number):number { return x + y } console.log(addNum(1,2)) //3 function log(message : string | number) : void { console.log(message) }
Interfaces
//Interfaces interface UserInterface { readonly id:number, name:string, age ?: number //optional } const user1 : UserInterface ={ id : 1, name : 'John' } //Since id is readOnly, it makes an error. user1.id = 5 interface MathFunc { (x:number, y:number) : number } const add : MathFunc = (x:number, y:number) :number =>x+y const sub : MathFunc = (x:number, y:number) :number =>x-y
Classes
interface PersonInterface { id:number, name:string, register() : string } class Person implements PersonInterface { id:number name : string constructor(id:number, name:string){ this.id = id this.name= name } register(){ return `${this.name} is now registered` } } const brad = new Person(1, 'Brad Traversy') const mike = new Person(2, 'Mike Jordan') console.log(brad.id) //make an error ,if id is private or protected //Subclasses class Employee extends Person { position : string constructor(id:number, name:string, position:string){ super(id, name) this.position= position } } const emp = new Employee(3, 'Shawn', 'Developer')
Generics
: 제네릭은 데이터의 타입을 일반화한다는 것을 의미
Generic은 자료형을 정하지 않고 여러 타입을 사용할 수 있게 해준다.
즉, 선언 시점이 아니라 생성 시점에 타입을 명시하여 하나의 타입만이 아닌
다양한 타입을 사용할 수 있도록 하는 기법
한 번의 선언으로 다양한 타입에 '재사용'이 가능하다는 장점
***any의 경우, 자료의 타입을 제한할 수 없고, 어떤 타입의 데이터가 리턴되는지 알 수 없다.
참고자료 : https://velog.io/@edie_ko/TypeScript-Generic-제네릭-feat.-TypeScript-두-달차-후기
//Generics function getArray<T>(items:T[]) : T[] { return new Array().concat(items) } let numArray = getArray<number>([1,2,3,4]) let strArray = getArray<string>(['brad', 'John', 'Sue']) numArray.push(1) //strArray.push(1) -> strArray는 string //numArray.push('hello') -> numArray는 number strArray.push('hello')
TypeScript with React
npx create-react-app . —template typescript
→ After then, js or jsx files would be changed into ts or tsx files.
//<Header.tsx> export interface Props { title : string color ?: string } const Header = (props:Props) => { return ( <header> <h1 style = {{color: props.color ? props.color : 'blue'}}>{props.title}</h1> </header> ) } export default Header
Originally posted on Notion :