TypeScript Essential Notes 4 - Custom Types

江洲
2023-12-01

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改成了匿名类型

 类似资料:

相关阅读

相关文章

相关问答