一. 概覽
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' ]