一. 概览
TypeScript中的类型缩小的方式有typeof、in等方式进行类型缩小。
二. 类型缩小
- typeof
function test(a: string| number | string []) {if(a) {if(typeof a === 'string') {} else if(typeof a === 'number') {}}
}
- in关键字
nterface ISideBar {hide: () =>void
}interface IModal {close(): void
}interface ITip {close?(): void;hide?: () =>void
}
type TypeComponent = ISideBar |  IModal | ITipfunction setClose(comp: TypeComponent ) {if( 'hide' in comp) {comp.hide()}comp.close()
}
comp也有可能是Itip类型,所以需要用类型断言
function setClose(comp: TypeComponent ) {if( 'hide' in comp) {(comp as ISideBar).hide()}(comp as IModal).close()
}
三. 类型谓词
之前有类型谓词的相关介绍 TypeScript中的 | 分隔符、& 运算符、类型谓词is,现在在此基础上加以补充
function isString(str: unknown): boolean{  return typeof str === 'string';  
}  function formatArr(str: unknown): string[] {  if (isString(str) && str !== '') {  return str.split("");  } else {  return [];  }  
}
有编译报错:
 (parameter) str: unknown
 对象的类型为 “unknown”。
引入类型谓词进行解决
function isString(str: unknown): str is string{  return typeof str === 'string';  
}  function formatArr(str: unknown): string[] {  if (isString(str) && str !== '') {  return str.split("");  } else {  return [];  }  
}
在 TypeScript 中,使用类型谓词 is 可以帮助我们限制函数的输入参数类型。但是,这种类型谓词并不能直接限制函数的返回值类型。
要限制函数的返回值类型,可以使用 TypeScript 中的类型别名和类型断言。通过定义一个类型别名,可以指定函数的返回值类型。然后,在函数内部使用类型断言来确保返回值符合预期的类型。
// 定义一个类型别名,指定返回值类型为字符串数组  
type StringArray = string[];  function isString(str: unknown): str is string {  return typeof str === 'string';  
}  // 定义一个函数,返回值为字符串数组  
function getStrings(): StringArray {  // 使用类型断言,将参数限制为字符串类型,并返回字符串数组  const strings: StringArray = [  'Hello',  'World',  'TypeScript'  ];  return strings;  
}  // 使用类型断言,将函数返回值限制为字符串数组类型  
const result = getStrings() as StringArray;  
console.log(result); // 输出: [ 'Hello', 'World', 'TypeScript' ]