
이 글은 ReactMasterClass강의를 보며 작성한 글입니다.
3월 29일에 작성됨
TypeScript는 JavaScript 기반으로한 프로그래밍 언어이다.TypeScript는 Strongly typed programming language이다.TypeScript는 프로그램을 돌리기 전에 무엇이 잘못되었는지 얘기해준다.즉 개발자들을 위한 좋은 도구라고 볼 수 있다!
기존 프로젝트에서 설정새로운 프로젝트에서 설정import styled from "styled-components";
const Container = styled.div``;
interface CircleProps {
bgColor: string;
}
// CircleProps에 bgColor가 있다는 것을 typescript는 알고 있음
function Circle({ bgColor }: CircleProps) {
return <Container />;
}
export default Circle;
<Container bgColor={bgColor} />이런식의 코드일 때 typescript는 container가 div이기 때문에 오류가 터질 것이다. 그래서 typescript에게 bgColor를 styled-component에 보내고 싶다고 할 것이다. 그럴때 아래처럼 적용시켜주면 될 것이다.interface ContainerProps {
bgColor: string;
}
const Container = styled.div<ContainerProps>``;
interface CircleProps {
bgColor: string;
borderColor?: string;
}
null ?? "hello" // "hello"
undefined ?? "hello" // "hello"
"hi" ?? "hello" // "hi"
interface ContainerProps {
bgColor: string;
borderColor: string;
}
interface CircleProps {
bgColor: string;
borderColor?: string;
}
<Container bgColor={bgColor} borderColor={borderColor ?? "white"} />;
interface CircleProps {
bgColor: string;
borderColor?: string;
text?: string;
}
function Circle({ bgColor, borderColor, text = "Default Text" }: CircleProps) {
return (
<Container bgColor={bgColor} borderColor={borderColor ?? "red"}>
{text}
</Container>
);
}
const [counter, setCounter] = useState(1);const [value, setValue] = useState<number | string>(1);이런식으로 사용할 수 있다.const onChange = (event) => {};const onChange = (event: React.FormEvent) => {};이런식으로 React내에 FormEvent를 사용해주면 된다.const onChange = (event: React.FormEvent<HTMLInputElement>) => {};이런식으로 사용해서 어떤 element가 event를 발생시킬지 특정할 수 있다.const {
currentTarget: { value },
} = event;
console.log(value); // value값이 바로 나옴!
// import original module declarations
import "styled-components";
// and extend them!
declare module "styled-components" {
export interface DefaultTheme {
textColor: string;
bgColor: string;
}
}
import { DefaultTheme } from "styled-components/dist/types";
export const lightTheme: DefaultTheme = {
bgColor: "white",
textColor: "black",
btnColor: "red",
};
export const darkTheme: DefaultTheme = {
bgColor: "black",
textColor: "white",
btnColor: "blue",
};
const Container = styled.div`
background-color: ${(props) => props.theme.bgColor};
`;
TypeScript는 JavaScript의 DLC(확장판)같다!