TypeScript 新手指南
  • 前言
  • 簡介
    • 什麼是 TypeScript
    • 安裝 TypeScript
    • Hello TypeScript
  • 基礎
    • 原始資料型別
    • 任意值
    • 型別推論
    • 聯合型別
    • 物件的型別——介面
    • 陣列的型別
    • 函式的型別
    • 型別斷言
    • 宣告檔案
    • 內建物件
  • 進階
    • 型別別名
    • 字串字面量型別
    • 元組
    • 列舉
    • 類別
    • 類別與介面
    • 泛型
    • 宣告合併
    • 延伸閱讀
  • 工程
    • 程式碼檢查
  • 感謝
Powered by GitBook
On this page
  • 語法
  • 例子:將一個聯合型別的變數指定為一個更加具體的型別
  • 參考

Was this helpful?

  1. 基礎

型別斷言

Previous函式的型別Next宣告檔案

Last updated 4 years ago

Was this helpful?

型別斷言(Type Assertion)可以用來手動指定一個值的型別。

語法

<型別>值

或

值 as 型別

在 tsx 語法(React 的 jsx 語法的 ts 版)中必須用後一種。

例子:將一個聯合型別的變數指定為一個更加具體的型別

,當 TypeScript 不確定一個聯合型別的變數到底是哪個型別的時候,我們只能訪問此聯合型別的所有型別裡共有的屬性或方法:

function getLength(something: string | number): number {
    return something.length;
}

// index.ts(2,22): error TS2339: Property 'length' does not exist on type 'string | number'.
//   Property 'length' does not exist on type 'number'.

而有時候,我們確實需要在還不確定型別的時候就訪問其中一個型別的屬性或方法,比如:

function getLength(something: string | number): number {
    if (something.length) {
        return something.length;
    } else {
        return something.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'.

上例中,存取 something.length 的時候會報錯。

此時可以使用型別斷言,將 something 斷言成 string:

function getLength(something: string | number): number {
    if ((<string>something).length) {
        return (<string>something).length;
    } else {
        return something.toString().length;
    }
}

型別斷言的用法如上,在需要斷言的變數前加上 <Type> 即可。

型別斷言不是型別轉換,斷言成一個聯合型別中不存在的型別是不允許的:

function toBoolean(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'.

參考

()

TypeScript Deep Dive / Type Assertion
Advanced Types # Type Guards and Differentiating Types
中文版
上一章:函式的型別
下一章:宣告檔案
之前提到過