Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA GEN AI SCIPY AWS CYBERSECURITY DATA SCIENCE
     ❯   

TypeScript 类型别名和接口


TypeScript 允许在使用类型的变量之外单独定义类型。

别名和接口允许在不同的变量/对象之间轻松共享类型。


类型别名

类型别名允许使用自定义名称(别名)定义类型。

类型别名可用于基本类型,如 string,或更复杂的类型,如 对象数组

示例

type CarYear = number
type CarType = string
type CarModel = string
type Car = {
  year: CarYear,
  type: CarType,
  model: CarModel
}

const carYear: CarYear = 2001
const carType: CarType = "Toyota"
const carModel: CarModel = "Corolla"
const car: Car = {
  year: carYear,
  type: carType,
  model: carModel
};
自己试试 »

接口

接口类似于类型别名,但它们**仅**适用于 对象 类型。

示例

interface Rectangle {
  height: number,
  width: number
}

const rectangle: Rectangle = {
  height: 20,
  width: 10
};
自己试试 »

w3schools CERTIFIED . 2022

获得认证!

完成 TypeScript 模块,完成练习,参加考试并成为 w3schools 认证专家!

45 美元 报名

扩展接口

接口可以扩展彼此的定义。

**扩展**接口意味着您正在创建一个具有与原始接口相同属性的新接口,以及一些新的属性。

示例

interface Rectangle {
  height: number,
  width: number
}

interface ColoredRectangle extends Rectangle {
  color: string
}

const coloredRectangle: ColoredRectangle = {
  height: 20,
  width: 10,
  color: "red"
};
自己试试 »

TypeScript 练习

通过练习测试自己

练习

为字符串创建一个类型别名,称为 carType

 carType = 
        

开始练习


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
[email protected]

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
[email protected]

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2024 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.