Usecases and Errors in TypeScript
Usecases and Errors usually in Typescript
type for filterIds
In the code below, the filter_ids
value is extracted from the query parameters of the incoming request req
. It first checks if req.query.filter_ids
exists and is of type string
, then it splits the string into an array using the split
method, maps each element to a number using map
, and casts the result as an array of FilterIds
.
const filterIds: FilterIds =
(req.query?.filter_ids as string | undefined)?.split(",")?.map((id: string) => +id) as FilterIds;
This code can be re-written in a more concise manner:
const filterIds: FilterIds =
(req.query?.filter_ids as string)?.split(",").map(Number) || [];
Best practices for nullish coalescing and optional chaining in Typescript
The original code snippet is using optional chaining and the ternary operator to extract the first match from a regular expression on an optional string, and assign it to a variable that can either be a string or null. In typescript, it's recommended to use nullish coalescing and the optional chaining operator together for more concise and readable code.
let updatedAddress2 = address2?.match(/\d+/g); // might be an array or undefined
updatedAddress2 = updatedAddress2 ? updatedAddress2[0] : null; // might be null or string
Recommended code:
const updatedAddress2: string | null = address2?.match(/\d+/g)?.[0] ?? null;
useEffect can only return Promise and undefined
useEffect(() => {
if (status === "unauthenticated")
// ❌ return router.replace("/");
router.replace("/");
}, [status]);
Expected 0 type arguments but got 1
This error usually occurs when you try to pass a type argument to a function that doesn't accept any type arguments.
For example, if you have a function that is defined as follows:
function myFunction() {
// function body
}
You cannot pass any type arguments to this function because it doesn't accept any.
So, if you try to call this function like this:
myFunction<string>(); // Error: Expected 0 type arguments, but got 1.
You will get the error Expected 0 type arguments, but got 1.
because you're trying to pass a type argument to a function that doesn't accept any.
To fix this error, you need to either remove the type argument, or modify the function definition to accept the type argument.