Typescript

김명성·2022년 2월 27일
0

typescript

목록 보기
7/8

Typescript 기초


typescript 환경
tsconfig 확인
styled.d.ts 확인
react-app-env.d.ts 확인

theme.ts 확인
npm i @types/styled-components확인


state의 type 설정

state가 2개의 type을 갖게 설정할 수 있다.

const [value, setValue] = useState<number|string>(0);

<type|type>으로 value의 state가 2개의 타입을 갖을 수 있게 만든다.


typescript로 event type 보호하기.

const onChange =
(event: React.FormEvent<HTMLInputElement>) =>
	const {
	currentTarget: { value },
	} = event;
// 어떤 이밴트를 받을지,
// 이밴트의 속성들을 자동완성으로 받을 수 있다.
	setValue(value);

const onSubmit = 
(event:React.FormEvent<HTMLFormElement>) => {
	event.preventDefault();
	}

SyntheticEvent - 기본적인 REACTJs버전의 이밴트.
REACT 공홈 확인.


Typescript에서 API로 받아온 JSON 데이터 가공하기

typescript에서 JSON 파일의 객체에 대한 타입을 손수 쓰는것은 시간 낭비이므로 Array prototype을 사용한다.
  1. 콘솔창에 받아온 데이터묶음(객체)을 오른쪽으로 클릭 후 전역변수로 저장한다

  2. temp1로 저장되는데, temp1의 키와 속성을 따로 분리하여 입력하면 된다.

  3. 키값 가져오기
    Object.keys(temp1).join()
    속성값 가져온 뒤 typeof로 타입으로 변환하고 join으로 해체하기
    Object.values(temp1).map( v => typeof v).join();


typescript 배열과 객체 type 정의하기.

배열,객체는 모두 object로 표기되는데 그게 무엇인지 직접 설명해주어야 한다. 그렇기에 인터페이스를 별도로 만들어 주어서 요소 타입을 기재한다.
interface Something{
       ...
  tags: ITag[];

}

interface ITag{
  coin_counter: number;
ico_counter: number;
id: string;
name: string;
}

0개의 댓글