functiongetLength(something:string|number):number {returnsomething.length;}// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.// Property 'length' does not exist on type 'number'.
而有時候,我們確實需要在還不確定型別的時候就訪問其中一個型別的屬性或方法,比如:
functiongetLength(something:string|number):number {if (something.length) {returnsomething.length; } else {returnsomething.toString().length; }}// index.ts(2,19): error TS2339: Property 'length' does not exist on type 'string | number'.// Property 'length' does not exist on type 'number'.// index.ts(3,26): error TS2339: Property 'length' does not exist on type 'string | number'.// Property 'length' does not exist on type 'number'.
functiontoBoolean(something:string|number):boolean {return <boolean>something;}// index.ts(2,10): error TS2352: Type 'string | number' cannot be converted to type 'boolean'.// Type 'number' is not comparable to type 'boolean'.