TypeScript Essential Notes 4 - Custom Types

本文介绍了如何使用TypeScript的接口定义数据成员和函数,展示如何扩展接口、使用枚举定义常量,并通过匿名类型和函数接口实例化。深入理解了自定义类型在JavaScript中的灵活性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Defining custom types with interfaces

TypeScript提供了3种自定义类型的方法:interfaces, classes, enums

var todo: Todo = {
  name: "R",
  completed: false,
};
var todo2 = <Todo>{...} //casting syntax强制类型转换,用这种也可以,前面加个<Todo>

Using interfaces to describe functions

In the previous videos, I showed you how to create an interface that describes the data members or methods of an object. This is great when you’re dealing with a simple object, but in addition to being a dynamic language, JavaScript is also a functional language, meaning that not only can you assign a function to a variable, like this, but that functions are also objects that can have their own properties and methods as well. In other words, this is also perfectly legitimate JavaScript code.

legitimate adj. 正当的,合理的;合法的,依法的;合法婚姻所生的;(君主)有合法王位继承权的;(与音乐喜剧、滑稽剧相对)正剧的

interface jQuery {
  (selecotr: string): HTMLElement; //没有名称的函数属性
  version: number;
}

var $ = <jQuery>function (selector) {
  //find dom element
};

$.version = 1.12;

var element = $("#container");
element.

Extending interface definitions

that’s the behavior that comes out of the box in the jQuery library.
这就是 jQuery 库中开箱即用的行为

TypeScript will let you extend any interface without actually changing the original definition, and it’s actually much simpler than you might expect. Rather than update the jQuery team’s interface, I could create a brand new interface that shares the same, exact name as the one I want to extend.

Defining constant values with enums

They’re a way to define a set of meaningful and constant values that you can use to replace the magic strings and numbers that you would otherwise use.
enum,用于替换魔法值,魔法值就是不知道是干嘛用的1234,便于代码阅读

interface Todo {
  name: string;
  state: TodoState;
}

enum TodoState {
  "New" = 1,
  "Active" = 2,
}

var state = TodoState.New;
TodoState[state] // "New" 用中括号取值,有点像数组

Defining anonymous types

var todo: {
  name: string;
};

function totalLength(x: { length: number }, y: string | any[]): number {
  var total: number = x.length + y.length;
  return total;
}

此处参数x改成了匿名类型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值