입문 : https://www.youtube.com/watch?v=GHHUjITelsA
실전 : https://www.youtube.com/watch?v=V9XLst8UEtk
TypeScript를 만들 때 React에서 templete 형태로 만들기 위한 명령어
npx create-react-app my-app --template typescript
파일 저장 형태 : name.ts (뒤에 ts를 붙이면 됨)
형태
number
string
boolean
null
undefined
any(다 수용가능한)
지정 형태
let a: number = 3;
let b: string = "haha";
let c: boolean = true;
let d:any = "anything";
타입 2개 지정 가능
let a : numbert | string : "2 in 1"
d = 3
d = "string"
배열 지정
let e:string[] = ['apple', 'mongo']
함수
function addNumber(a:number, b:number):number{
return a+b
}
addNumber(3,7)
실행방법(노드는 ts를 읽지 못한다.)
node {파일명} 은 실행 불가
tsc {파일명} 은 실행 가능
tsc로 실행시킬 경우에에는 추가로 js파일을 만들어주고 그걸로 실행시킬 수 있게끔 한다.
tsconfig.json(설정정보 입력)
"files" 속성 사용하기
{
"compilerOptions": {
"module": "commonjs",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"sourceMap": true
"target": "es5",
"module": "commonjs",
"noImplicitAny": true,
"strictNullChecks": true
},
"files": [
"core.ts",
"sys.ts",
"types.ts",
"scanner.ts",
"parser.ts",
"utilities.ts",
"binder.ts",
"checker.ts",
"emitter.ts",
"program.ts",
"commandLineParser.ts",
"tsc.ts",
"diagnosticInformationMap.generated.ts"
]
}
"include" 와 "exclude" 속성 사용하기
{
"compilerOptions": {
"module": "system",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outFile": "../../built/local/tsc.js",
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
주석 포함 설명
{
"compilerOptions": {
"target": "es5", // 'es3', 'es5', 'es2015', 'es2016', 'es2017','es2018', 'esnext' 가능
"module": "commonjs", //무슨 import 문법 쓸건지 'commonjs', 'amd', 'es2015', 'esnext'
"allowJs": true, // js 파일들 ts에서 import해서 쓸 수 있는지
"checkJs": true, // 일반 js 파일에서도 에러체크 여부
"jsx": "preserve", // tsx 파일을 jsx로 어떻게 컴파일할 것인지 'preserve', 'react-native', 'react'
"declaration": true, //컴파일시 .d.ts 파일도 자동으로 함께생성 (현재쓰는 모든 타입이 정의된 파일)
"outFile": "./", //모든 ts파일을 js파일 하나로 컴파일해줌 (module이 none, amd, system일 때만 가능)
"outDir": "./", //js파일 아웃풋 경로바꾸기
"rootDir": "./", //루트경로 바꾸기 (js 파일 아웃풋 경로에 영향줌)
"removeComments": true, //컴파일시 주석제거
"strict": true, //strict 관련, noimplicit 어쩌구 관련 모드 전부 켜기
"noImplicitAny": true, //any타입 금지 여부
"strictNullChecks": true, //null, undefined 타입에 이상한 짓 할시 에러내기
"strictFunctionTypes": true, //함수파라미터 타입체크 강하게
"strictPropertyInitialization": true, //class constructor 작성시 타입체크 강하게
"noImplicitThis": true, //this 키워드가 any 타입일 경우 에러내기
"alwaysStrict": true, //자바스크립트 "use strict" 모드 켜기
"noUnusedLocals": true, //쓰지않는 지역변수 있으면 에러내기
"noUnusedParameters": true, //쓰지않는 파라미터 있으면 에러내기
"noImplicitReturns": true, //함수에서 return 빼먹으면 에러내기
"noFallthroughCasesInSwitch": true, //switch문 이상하면 에러내기
}
}
맥북
cmd + shift + b = tsc.build
윈도우
터미널에서 tcs 명령어 실행
실행하면 dist 폴더가 생기고 하위 파일로 js 파일이 들어감
let data = {
name:"누나네식당",
category:"western",
address:{
city:"incheoi",
detail: "somewhere",
zipcode: 123456
},
menu:[{name:"rose pasta", price:2000, category:"PASTA"},{name:"stake", price:4000, category:"STAKE"}]
}
const App.React.Fc = () => {
return(
<div className="App">
<Store info={data}>
</div>
)
}
model 폴더를 만들어서 데이터에 대한 타입을 저정해준다.
model / resturant.ts
export type Resturant = {
name:string;
category:string;
//address:{
//city:string;
//detail:string;
//zipCode:Number;
//};
//menu:{
//name:string;
//price:number;
//catagory:string;
//}[]
menu:Menu[]
}
export type Address = {
city:string;
detail:string;
zipCode:Number;
}
export type menu = {
name:string;
price:number;
catagory:string;
}
리액트 hook 사용
앞에 <> 기호로 형 을 넣어주는 것을 필수로 할 것(그래야 타입을 알 수 있으니까)
import Store from './Store';
import {Restaurant} from "./model/resturant";
let data = {
name:"누나네식당",
category:"western",
address:{
city:"incheoi",
detail: "somewhere",
zipcode: 123456
},
menu:[{name:"rose pasta", price:2000, category:"PASTA"},{name:"stake", price:4000, category:"STAKE"}]
}
const App.React.Fc = () => {
const [myRestaurant, setMyResuaurant] = useState<Restaurant>(data)
return(
<div className="App">
<Store info={data}>
</div>
)
}
인터페이스 사용법
import React from 'react'
interface OwnProps {
info:Restaurant
}
const Store.React.FC<OwnProps> = (props) => {
return (
<div>Store</div>
)
}
export default Store
함수 보내는 법
import Store from './Store';
import {Address, Restaurant} from "./model/resturant";
let data = {
name:"누나네식당",
category:"western",
address:{
city:"incheoi",
detail: "somewhere",
zipcode: 123456
},
menu:[{name:"rose pasta", price:2000, category:"PASTA"},{name:"stake", price:4000, category:"STAKE"}]
}
const App.React.Fc = () => {
const [myRestaurant, setMyResuaurant] = useState<Restaurant>(data);
//보내는 방법은 간단하다. 대신 import해야함
const changeAddress = (address) =>{
setMyRestaurant({...myRestaurant, assress:Address})
}
return(
<div className="App">
<Store info={data}>
</div>
)
}
import React from 'react'
interface OwnProps {
info:Restaurant
changeAddress(address:Address):void
}
const Store.React.FC<OwnProps> = (props) => {
return (
<div>Store</div>
)
}
export default Store
extends
model / resturant.ts
export type Resturant = {
name:string;
category:string;
address:Address;
menu:Menu[]
}
export type Address = {
city:string;
detail:string;
zipCode:Number;
}
export type menu = {
name:string;
price:number;
catagory:string;
}
const App.React.Fc = () => {
const [myRestaurant, setMyResuaurant] = useState<Restaurant>(data);
//보내는 방법은 간단하다. 대신 import해야함
const changeAddress = (address) =>{
setMyRestaurant({...myRestaurant, assress:Address})
}
const showBestMenuName = (name:string) => (
return name
)
return(
<div className="App">
<Store info={myRestaurant} changeAddress={changeAddress} />
<BestMenu name="불고기피자" category="피자" price={1000}/ showBestMenuName={showBestMenuName}>
</div>
)
}
import React from 'react'
interface OwnProps extends Menu{
showBestMenuName(name:string):string
}
//위 인터페이스와 같은 내용
type OwnProps = Menu & {
showBestMenuName(name:string):string
}
const BestMenu:React.FC<OwnProps>= ({name, price, category, showBestMenuName}) =>{
return (
<div>BestMenu</div>
<div>{name}</div>
)
}
export default BestMenu
omit / Pick
model / resturant.ts
export type Resturant = {
name:string;
category:string;
address:Address;
menu:Menu[]
}
export type Address = {
city:string;
detail:string;
zipCode:Number;
}
export type menu = {
name:string;
price:number;
catagory:string;
}
export type AddressWithoutZip = Omit<Address, 'zipcode'>
export type RestaurantOnlyCategory = Pick<Restaurant, 'category'>
인터페이스에서도 뺄 수 있다.
import React from 'react'
// Omit으로 유동적으로 type을 작성할 수 있게끔
interface OwnProps extends Omit<Menu,'price'>{
showBestMenuName(name:string):string
}
const BestMenu:React.FC<OwnProps>= ({name, price, category, showBestMenuName}) =>{
return (
<div>BestMenu</div>
<div>{name}</div>
)
}
export default BestMenu
api로 데이터를 받을 때 타입 형태로 받을 수 있게끔 하는 방법