- Strongly-typed JavaScript이다.
- 개발자가 JavaScript를 사용하는 과정에서 발생하는 다양한 오류들(실수들)을 잡는데 도움을 준다.
- TypeScript로 작성된 Code는 Compiler를 통해 JavaScript로 변환된다.
## Interface
- Component의 Props의 타입(OR Object의 Shape)을 지정할 수 있다.
- 이를 통해 코드 실행 **전**에 에러를 볼 수 있다.
```jsx
interface ContainerProps {
bgColor: string;
}
const Container = styled.div<ContainerProps>`
width: 200px;
height: 200px;
background-color: ${(props) => props.bgColor};
border-radius: 50%;
`;
interface CircleProps {
bgColor: string;
}
function Circle({bgColor}: CircleProps) {
return <Container bgColor={bgColor}/>
}
```
## Optional
- TypeScript으로 지정된 Props들을 기본적으로 **Required** 상태이다.
- **Required**가 아닌 **Optional**로 타입을 지정하기 위해서는 `:` 가 아닌 `?:` 기호를 사용하면 된다.
```jsx
interface CircleProps {
bgColor: string;
borderColor?: string;
}
function Circle({ bgColor, borderColor }: CircleProps) {
return <Container bgColor={bgColor} borderColor={borderColor} />
}
```
- CSS 해당 Props를 통해 스타일링을 할 경우 Default Value를 지정해주어야 한다.
- Default Value를 지정해주는 방식은 2가지로
- **Argument**에서 Default 값을 설정하는 방법
- `??` Syntax를 활용해 값이 없을 시 다른 값을 **Parameter**에 넘겨주는 방법
```jsx
interface ContainerProps {
bgColor: string;
borderColor: string;
}
const Container = styled.div<ContainerProps>`
width: 100px;
height: 100px;
background-color: ${(props) => props.bgColor};
border-radius: 50%;
border: 1px solid ${(props) => props.borderColor};
`;
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
function Circle({ bgColor, borderColor, text = "default text" }: CircleProps) {
return <Container bgColor={bgColor} borderColor={borderColor ?? "transparent"} >{text}</Container>
}
```
## State
- React의 UseState를 사용할 때 초기 값을 기준으로 TypeScript가 해당 값들의 타입을 지정해준다.
![[State.png]]
- 만약에 State가 여러 개의 타입을 가질 수 있게 하고 싶으면 `|` Operator를 사용해 직접 지정해 줄 수 있다. (거의 사용할 일은 없다.)
```jsx
const [value, setValue] = useState<number|string>(0);
```
## Event
- **Change**나 **Form**같은 **Event**를 TypeScript로 지정할 수 있다.
- 이를 통해 해당 Event를 사용하기 더 수월해진다.
```jsx
function App() {
const [username, setUsername] = useState("");
const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const {
currentTarget: {value},
} = event;
setUsername(value);
}
const onSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log(username);
}
return (
<form onSubmit={onSubmit}>
<input value={username} onChange={onChange} type="text" placeholder="Username" />
<button>Login</button>
</form>
);
}
```
## Declaration File
- `d.ts` 확장자를 가진 파일로 각각의 타입을 지정해 **TypeScript**가 알아볼 수 있도록 해준다.
- 대부분의 경우 **npm**에서 다른 훌륭한 개발자들이 만들어 놓은 것을 다운로드해서 사용하지만 특수한 경우 이를 **Overriding**하여 독자적으로 만들 필요가 있다.
```jsx
//styled.d.ts에서 Default Theme Type을 지정한다.
import 'styled-components';
declare module 'styled-components' {
export interface DefaultTheme {
textColor: string;
backgroundColor: string;
}
}
```