Skip to main content

19 posts tagged with "JS/HTML/CSS"

View all tags

TypeScript Enum

· 11 min read
Kimi Gao
Fullstack & AI

枚举(Enum)类型经常被用于取值在一定范围内的场景,比如一周只能有七天,角色权限设计等。枚举类型变量使用enum字段来定义,枚举成员的值可以是数字或者字符串,并且枚举成员是只读的。

枚举按照类型划分,主要分为以下三种:

TypeScript Type Compatibility

· 18 min read
Kimi Gao
Fullstack & AI

TS 允许将一些不同类型的变量相互赋值,虽然某种程度上可能会产生一些不可靠的行为,但增加了语言的灵活性,毕竟它的祖宗 JS 就是靠灵活性起家的,而灵活性已经深入前端的骨髓,有时会不得不做一些妥协。

当一个类型 Y 可以被赋值给另一个类型 X 时,我们就可以说类型 X 兼容类型 Y

X (目标类型) = Y (源类型)

Primitive type compatibility

原始类型的兼容性主要关注三点:

TypeScript Generic Function

· 6 min read
Kimi Gao
Fullstack & AI

概述

泛型即不预先确定的数据类型,具体的类型在使用的时候才能确定。本节将学习ts中的泛型函数。

在软件工程中,开发定义良好且可重用的组件是非常重要的,因为这确保了程序的灵活性和长期可扩展性。使用泛型可以创建可重用的组件,一个组件可以支持多种类型的数据,而用户就可以根据自己的需要的数据类型来使用组件。

泛型函数

什么是泛型函数

概述中泛型的概念比较抽象,为了理解什么是泛型函数,我们可以结合一个例子来说明。

如下例所示,identity函数返回传入的参数,但是这个函数的可重用性很差,只能支持number类型。

function identity(arg: number): number {
return arg;
}

为了支持更多的类型,我们可以将参数设置为联合类型或者any类型。

TypeScript Interface: Extend or implement

· 2 min read
Kimi Gao
Fullstack & AI

Interface extends interface

Interfaces can extend one or more interfaces. This makes writing interfaces flexible and reusable.

interface Person {
name: string;
gender: string;
}

interface Employee extends Person {
department: string;
}

let empObj: Employee = {
name: 'Kimi',
gender: 'male',
department: 'Payment',
};

Type Script Interface: As Object Or Array Type

· 6 min read
Kimi Gao
Fullstack & AI

Interface in TypeScript can be used to define a type and also to implement it in the class. The most scenarios can be summarized as following:

  • as object type definition
  • as array type definition
  • as function type definition
  • interface extends interface
  • class implements interface

In this section, we mainly focus on the object and array type definition using interface. As function type definition will be introduced in Function: Types section.

Interface likes contract which defines the structure of the object, array, function and also class. However, we need to note that the TypeScript compiler does not convert interface to JavaScript. It uses interface for type checking.