변수에 값을 저장해야하는데 코드를 작성할 시점에 값의 타입(써드파티 API나 유저 입력값 등)을 모르면 사용함.
any type으로 하면 컴파일 시에 타입 체크 건너뜀.
// json may come from a third-party API
const json = `{"latitude": 10.11, "longitude":12.12}`;
// parse JSON to find location
const currentLocation = JSON.parse(json);
console.log(currentLocation);
Output:
{ latitude: 10.11, longitude: 12.12 }
근데
console.log(currentLocation.x);
를 하면 undefeined로 나옴. 그냥 자바스크립트처럼 하는거기 때문에 자바스크립트 프로젝트를 타입스크립트로 바꿀때 사용할 수도 있음.
let result;
위 처럼 타입 명시하지 않고 변수 선언하면 any type이 되는데 이를 type inference라고 함.
let result: any;
result = 10.123;
console.log(result.toFixed());
result.willExist(); //
위 코드에서 any type이어서 컴파일시점에 willExist()가 없어도 런타임 시점에는 있을 수 있기에 에러 안 뱉음.
let result: object;
result.toFixed();
위 처럼 object type으로 바꾸면 컴파일러가 toFixed()가 없다고 에러 뱉음.
- any type으로 아무 타입이나 저장가능하고 컴파일러한테 type check 건너뛰게함
- 컴파일 시점에 타입을 알 수 없는 값을 저장할때 사용함