TS는 JS에서 새로운 기능만 더해진 언어라고 생각하면 된다.
TS는 작동하기 전에 데이터타입을 확인하는 기능을 가진다.
변수를 사용할 때 어떤 데이터 타입인지 명시해줘야하고 해당 데이터 타입이 아닐 경우에는 바로 오류를 발생시킨다.
const plus = (a:number, b:number) => a + b;
브라우저는 TS를 이해하지 못 하지만 컴파일 후 JS로 변환되기 때문에 문제없이 사용할 수 있다.
TS를 기존 JS 기반의 프로젝트에 설치하려면 이것저것 재설정 해주어야 하기 때문에 그냥 새롭게 리액트 앱을 생성했다..ㅎㅎ
npx create-react-app <앱 이름> --template typescript
그리고 스타일 컴포넌트를 사용하기 위해서 몇가지를 더 설치해주었다.
npm i --save-dev @types/styled-components
npm i styled-components
인터페이스란 객체 모양을 TS에게 설명해주는 것이다.
사용되는 props를 객체에 담아 type을 지정한다.
interface ContainerProps {
bgColor: string;
}
const Container = styled.div<ContainerProps>`
width: 100px;
height: 100px;
background-color: ${(props) => props.bgColor};
`;
interface CircleProps {
bgColor: string;
}
function Circle({ bgColor }: CircleProps) {
return <Container bgColor={bgColor} />;
}
이 예시에서는 두 개의 인터페이스가 있다.
두 인터페이스는 각각 다른 props의 데이터 타입을 감시한다.
props를 선택적으로 사용하여 인터페이스를 만들 수도 있다.
아래와 같이 props 키 옆에 ?만 붙여주면 borderColor라는 props는 있어도 되고 없어도 되는 것이 된다.
...
interface CircleProps {
bgColor: string;
borderColor?: string;
}
function Circle({ bgColor, borderColor }: CircleProps) {
return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}/>;
}
여기서 Circle의 인터페이스는 borderColor를 선택적으로 가지고 Container의 인터페이스는 필수적으로 가진다.
이 경우 Circle에서 borderColor값을 넘겨주지 않았을 경우 에러가 발생할 수 있기 때문에 borderColor의 초깃값을 설정해준다.
TS는 우리가 설정한 state의 초기값으로 state의 타입을 추론하기 때문에 setState함수로 다른 타입으로 state를 변경할 시에는 에러를 발생시킨다.
대부분의 경우 처음 설정한 state의 타입을 계속 사용하지만 필요에 따라 데이터 타입을 바꿀 일이 생길 수도 있다.
그 경우에는 state의 데이터타입을 여러개로 지정하여 해당 에러를 방지할 수 있다.
const [value, setValue] = useState<number|string>(0);
이렇게 하면 value의 값은 number 혹은 string이라고 TS에게 알려줄 수 있다.
간단한 예시를 들 수 있다.
function App() {
const [value, setValue] = useState("");
const onChange = (event: React.FormEvent<HTMLInputElement>) => {
const { value } = event.currentTarget;
setValue(value);
};
return (
<div>
<input value={value} onChange={onChange} />
</div>
);
}
이벤트 핸들러는 모든 브라우저에서 이벤트를 동일하게 처리하기 위한 이벤트 래퍼 SyntheticEvent 객체를 전달받는다.
https://reactjs.org/docs/events.html
**응용
TS와 스타일컴포넌트의 Theme를 연결해볼 것이다.
1. declaration파일인 styled.d.ts를 만들어 테마를 포함시켜 확장한다.
// 기존 스타일 컴포넌트를 불러온다.
import "styled-components";
// 확장한다.
declare module "styled-components" {
export interface DefaultTheme {
bgColor: string;
textColor: string;
}
}
2. 테마가 담긴 파일(theme.ts)를 만든다.
import { DefaultTheme } from "styled-components";
const theme: DefaultTheme = {
bgColor: "white",
textColor: "black",
};
만든 테마를 웹에 직접 사용하는 방법은 이전 게시물에서 설명했던 것과 동일하다.
'Tech > TypeScript' 카테고리의 다른 글
[Typescript / TS] Frame motion을 사용한 애니메이션 (0) | 2023.01.29 |
---|---|
[Typescript / TS] ToDo 칸반보드 만들기 (0) | 2023.01.23 |
[Typescript / TS] ToDo리스트 만들기 (0) | 2023.01.16 |
[Typescript / TS] Recoil을 사용한 state 관리 (0) | 2023.01.16 |
[Typescript / TS] 코인트래킹 어플 만들기 (0) | 2023.01.07 |
TS는 JS에서 새로운 기능만 더해진 언어라고 생각하면 된다.
TS는 작동하기 전에 데이터타입을 확인하는 기능을 가진다.
변수를 사용할 때 어떤 데이터 타입인지 명시해줘야하고 해당 데이터 타입이 아닐 경우에는 바로 오류를 발생시킨다.
const plus = (a:number, b:number) => a + b;
브라우저는 TS를 이해하지 못 하지만 컴파일 후 JS로 변환되기 때문에 문제없이 사용할 수 있다.
TS를 기존 JS 기반의 프로젝트에 설치하려면 이것저것 재설정 해주어야 하기 때문에 그냥 새롭게 리액트 앱을 생성했다..ㅎㅎ
npx create-react-app <앱 이름> --template typescript
그리고 스타일 컴포넌트를 사용하기 위해서 몇가지를 더 설치해주었다.
npm i --save-dev @types/styled-components
npm i styled-components
인터페이스란 객체 모양을 TS에게 설명해주는 것이다.
사용되는 props를 객체에 담아 type을 지정한다.
interface ContainerProps {
bgColor: string;
}
const Container = styled.div<ContainerProps>`
width: 100px;
height: 100px;
background-color: ${(props) => props.bgColor};
`;
interface CircleProps {
bgColor: string;
}
function Circle({ bgColor }: CircleProps) {
return <Container bgColor={bgColor} />;
}
이 예시에서는 두 개의 인터페이스가 있다.
두 인터페이스는 각각 다른 props의 데이터 타입을 감시한다.
props를 선택적으로 사용하여 인터페이스를 만들 수도 있다.
아래와 같이 props 키 옆에 ?만 붙여주면 borderColor라는 props는 있어도 되고 없어도 되는 것이 된다.
...
interface CircleProps {
bgColor: string;
borderColor?: string;
}
function Circle({ bgColor, borderColor }: CircleProps) {
return <Container bgColor={bgColor} borderColor={borderColor ?? bgColor}/>;
}
여기서 Circle의 인터페이스는 borderColor를 선택적으로 가지고 Container의 인터페이스는 필수적으로 가진다.
이 경우 Circle에서 borderColor값을 넘겨주지 않았을 경우 에러가 발생할 수 있기 때문에 borderColor의 초깃값을 설정해준다.
TS는 우리가 설정한 state의 초기값으로 state의 타입을 추론하기 때문에 setState함수로 다른 타입으로 state를 변경할 시에는 에러를 발생시킨다.
대부분의 경우 처음 설정한 state의 타입을 계속 사용하지만 필요에 따라 데이터 타입을 바꿀 일이 생길 수도 있다.
그 경우에는 state의 데이터타입을 여러개로 지정하여 해당 에러를 방지할 수 있다.
const [value, setValue] = useState<number|string>(0);
이렇게 하면 value의 값은 number 혹은 string이라고 TS에게 알려줄 수 있다.
간단한 예시를 들 수 있다.
function App() {
const [value, setValue] = useState("");
const onChange = (event: React.FormEvent<HTMLInputElement>) => {
const { value } = event.currentTarget;
setValue(value);
};
return (
<div>
<input value={value} onChange={onChange} />
</div>
);
}
이벤트 핸들러는 모든 브라우저에서 이벤트를 동일하게 처리하기 위한 이벤트 래퍼 SyntheticEvent 객체를 전달받는다.
https://reactjs.org/docs/events.html
**응용
TS와 스타일컴포넌트의 Theme를 연결해볼 것이다.
1. declaration파일인 styled.d.ts를 만들어 테마를 포함시켜 확장한다.
// 기존 스타일 컴포넌트를 불러온다.
import "styled-components";
// 확장한다.
declare module "styled-components" {
export interface DefaultTheme {
bgColor: string;
textColor: string;
}
}
2. 테마가 담긴 파일(theme.ts)를 만든다.
import { DefaultTheme } from "styled-components";
const theme: DefaultTheme = {
bgColor: "white",
textColor: "black",
};
만든 테마를 웹에 직접 사용하는 방법은 이전 게시물에서 설명했던 것과 동일하다.
'Tech > TypeScript' 카테고리의 다른 글
[Typescript / TS] Frame motion을 사용한 애니메이션 (0) | 2023.01.29 |
---|---|
[Typescript / TS] ToDo 칸반보드 만들기 (0) | 2023.01.23 |
[Typescript / TS] ToDo리스트 만들기 (0) | 2023.01.16 |
[Typescript / TS] Recoil을 사용한 state 관리 (0) | 2023.01.16 |
[Typescript / TS] 코인트래킹 어플 만들기 (0) | 2023.01.07 |