interface Foo { foo: string; }
interface Bar { bar: string; }
declare function expressionReturningFoo(): Foo;
function processBar(b: Bar) { /* ... */ }
function f1() {
const x: any = expressionReturningFoo(); // Don't do this
processBar(x);
}
function f2() {
const x = expressionReturningFoo();
processBar(x as any); // Prefer this
}
interface Foo { foo: string; }
interface Bar { bar: string; }
declare function expressionReturningFoo(): Foo;
function processBar(b: Bar) { /* ... */ }
function f1() {
const x: any = expressionReturningFoo();
processBar(x);
return x;
}
function g() {
const foo = f1(); // Type is any
foo.fooMethod(); // This call is unchecked!
}
interface Foo { foo: string; }
interface Bar { bar: string; }
declare function expressionReturningFoo(): Foo;
function processBar(b: Bar) { /* ... */ }
function f1() {
const x = expressionReturningFoo();
// @ts-ignore
processBar(x);
return x;
}
function getLengthBad(array: any) { // Don't do this!
return array.length;
}
function getLength(array: any[]) {
return array.length;
}
getLengthBad(/123/); // No error, returns undefined
getLength(/123/);
// ~~~~~ Argument of type 'RegExp' is not assignable
// to parameter of type 'any[]'
function getLengthBad(array: any) { // Don't do this!
return array.length;
}
function getLength(array: any[]) {
return array.length;
}
function hasTwelveLetterKey(o: {[key: string]: any}) {
for (const key in o) {
if (key.length === 12) {
return true;
}
}
return false;
}
function getLengthBad(array: any) { // Don't do this!
return array.length;
}
function getLength(array: any[]) {
return array.length;
}
type Fn0 = () => any; // any function callable with no params
type Fn1 = (arg: any) => any; // With one param
type FnN = (...args: any[]) => any; // With any number of params
// same as "Function" type
declare function shallowEqual(a: any, b: any): boolean;
function shallowObjectEqual<T extends object>(a: T, b: T): boolean {
for (const [k, aVal] of Object.entries(a)) {
if (!(k in b) || aVal !== (b as any)[k]) {
return false;
}
}
return Object.keys(a).length === Object.keys(b).length;
}
function somethingDangerous() {}
let val = null; // Type is any
try {
somethingDangerous();
val = 12;
val // Type is number
} catch (e) {
console.warn('alas!');
}
val // Type is number | null
<이펙티브 타입스크립트> (댄 밴더캅 지음, 장원호 옮김, 인사이트, 2021)