깊고 넓은 삽질

[typescript / error] unknown 타입으로 전달되는 객체의 속성 사용하기 본문

Programming

[typescript / error] unknown 타입으로 전달되는 객체의 속성 사용하기

ggsno 2022. 8. 23. 03:47

🏁 목적 | jwt 토큰을 디코딩한 객체의 특정 value값을 storage에 넣기

◼ 토큰을 디코딩해서 디코딩된 토큰 객체의 user_id 값을 사용하고 싶었다.

❌ 문제 | 객체의 속성을 못 찾음

당연함. 디코딩된게 뭐가 될지 모름.

그럼 디코딩된 토큰이 내가 생각하는 객체인지 확인해주는 타입가드를 넣으면 어떨까?

환장하것네

✅ 해결 | 사용자 정의 타입가드 함수 사용

구글링 해보니 is라는 ts문법으로 사용자정의 타입가드를 할 수 있단다

https://bobbyhadz.com/blog/typescript-check-if-unknown-has-property

 

Check if Value with Unknown Type contains Property in TS | bobbyhadz

Use a user-defined type guard to check if a value with `unknown` type contains a property in TypeScript. The user-defined type guard consists of a function that checks if the specific property is contained in the object and returns a predicate.

bobbyhadz.com

어렵다 어려워

 

Comments