Learning notes from a few advanced topics in typescript
Frontend Engineering Manager
Certa - No Code workflow management and automation (SAAS)
Typescript
ReactJS
@rajatvijay
@rajatvijay
Leveraging type safety for the data fetched at runtime
Treating types as code
Never miss a case to handle ever
A type guard is some expression that performs a runtime check that guarantees the type in some scope.
-- TS Docs
let data:any;
// Inferred type is any
data;
if (typeof data === "number") {
// Inferred type is number
data;
}
function fetchCount() {
return axios
.get("API_URL")
.then((response) => response.data)
.then((response) => {
// Inferred type as any
response;
assertIsNumber(response);
// Inferred type as number
return response;
});
}
// Initially
fetchCount: () => Promise<any>
// After using type guards
fetchCount: () => Promise<number>
type Employee = {
id: string;
employee_name: string;
employee_salary: string;
employee_age: string;
profile_image: string;
};
export const getEmployees = async () => {
const response = await axios.get(
"http://dummy.restapiexample.com/api/v1/employees"
);
const responseFromAPI = response.data;
// Inferred type is any
responseFromAPI;
assertIsEmployeeArray(responseFromAPI);
// Inferred type is Employee[]
responseFromAPI;
return responseFromAPI;
};
Implement `assertIsEmployeeArray`
function func(value: Function|Date|number[]) {
if (typeof value === 'function') {
// Inferred typs is Function
value;
}
if (value instanceof Date) {
// Inferred typs is Date
value;
}
if (Array.isArray(value)) {
// Inferred typs is number[]
value;
}
}
They change and grow over time
Jest cannot test the changes in your time, it only tests the compiled code
TSD to the rescue
Still there are valid use cases for them!
Usually used for large no of cases
Typescript's `never` type
@rajatvijay
@rajatvijay