Do not use any
unless necessary
Thursday, November 7, 2019
Do not use any
unless necessary
Do not use TypeScript's any
type because this removes the ability of the TypeScript compiler to perform type checking in your code. The TypeScript compiler performs in-depth type checking that can reduce typos and potential errors. When you specify the any
type, either explicitly or implicitly, the compiler will no longer perform type checking on the variable or argument, and when used as the return type of a function, on any operations performed on the value returned.
It is important to also know that the default return type of a function is any
where the return type cannot be inferred by the compiler.
Instructions
set the expected type, or type union, of a variable or function argument when declared but no value is immediately defined
explicitly setting the type of an argument or variable to any
implicitly setting the type of a variable to any
by not specifying the type when declaring the variable and the variable is not immediately defined
implicitly setting the return type of a function to any
by not explicitly specifying the return type, and the TypeScript compiler is unable to infer the type
the any
type removed the TypeScript compiler's ability to type check your code
Code Examples
explicitly set the type for variables not immediately defined a value
/** The return type is inferred to the type union `string | number` */
function testing(valid: boolean, something: string) {
let value: string | number;
if (valid) {
value = 'test';
} else if (something === 'else') {
value = 0;
}
return value;
}
explicitly set the type for variables as well as the return type of functions
/** The return type is explicitly set to the type union `string | number` */
function testing(valid: boolean, something: string): string | number {
let value: string | number;
if (valid) {
value = 'test';
} else if (something === 'else') {
value = 0;
}
return value;
}
implied any
type of a variable not immediately defined a value
/** Return type is inferred to `any`. */
function testing(valid: boolean, something: string) {
/** The `value` variable is not immediately defined, and no type is explicitly set. */
let value;
if (valid) {
value = 'test';
} else if (something === 'else') {
value = 0;
}
return value;
}
Have a question or comment?