首页 > 其他分享 >[TS手册学习] 04_对象类型

[TS手册学习] 04_对象类型

时间:2023-11-30 16:23:13浏览次数:39  
标签:string 04 number TS 类型 interface 手册 type name

TS官方手册:TypeScript: Handbook - The TypeScript Handbook (typescriptlang.org)

匿名与具名

对象类型的声明可以是匿名的,也可以使用interfacetype进行具名声明。

function greet(person: { name: string; age: number }) {
  return "Hello " + person.name;
}
interface Person {
  name: string;
  age: number;
}
 
function greet(person: Person) {
  return "Hello " + person.name;
}
type Person = {
  name: string;
  age: number;
};
 
function greet(person: Person) {
  return "Hello " + person.name;
}

可选属性 optional

使用?标记:

interface PaintOptions {
  shape: Shape;
  xPos?: number;
  yPos?: number;
}

注:使用PaintOptions声明的对象,它的xPos属性会被初步推断为number | undefined类型。

可以使用条件语句或者解构+默认值的方式收束类型,排除undefined的情况:

function paintShape(opts: PaintOptions) {
    let xPos = opts.xPos === undefined ? 0 : opts.xPos;
    // xPos 的类型为number
}
function paintShape({ shape, xPos = 0, yPos = 0 }: PaintOptions) {
	// xPos 的类型为number,因为undefined会被默认值0取代
    console.log("x coordinate at", xPos);
}

只读属性 readonly

interface SomeType {
    readonly prop: string;
}

注:如果有一个属性的值是引用值,例如一个对象或数组,且这个属性被标记为只读(readonly),我们不能修改它的引用值,但是可以修改它的内部属性。

interface Home {
  readonly resident: { name: string; age: number };
}

function visitForBirthday(home: Home) {
  // 我们可以读取并且更新'home.resident'里的属性
  console.log(`Happy birthday ${home.resident.name}!`);
  home.resident.age++;
}
 
function evict(home: Home) {
  // 但我们不能更新'home.resident'本身
  home.resident = {
Cannot assign to 'resident' because it is a read-only property.
    name: "Victor the Evictor",
    age: 42,
  };
}

索引签名 index signatures

interface StringArray {
  [index: number]: string;
}
 
const myArray: StringArray = getStringArray();
const secondItem = myArray[1];

索引的类型只能是:stringnumbersymbol,以及与这些类型相关的联合类型。

通常只会考虑stringnumber类型的索引。

:可以同时支持stringnumber两种类型的索引器,但数字索引器返回的类型必须是字符串索引器返回类型的子类型。这是因为当使用数字进行索引时,JS 实际上会在索引到对象之前将其转换为字符串。于是使用100"100"进行索引的结果是一样的。

当指定string类型索引的类型为S后,所有属性的类型都需要是S的子集。

interface NumberDictionary {
    [index: string]: number;

    length: number; // ok
    name: string; // NOT ok
}

这是因为当我们访问obj.a的时候,其实也是在访问obj["a"]

在上面这个例子中,string类型索引被声明为number类型,这意味着这个对象的所有属性都是number类型,而下方name却被声明为string类型,矛盾了。

可以使用联合类型解决这个问题:

interface NumberDictionary {
    [index: string]: number | string;

    length: number; // ok
    name: string; // ok
}

同时,索引签名也可以设置为只读:

interface ReadonlyStringArray {
  readonly [index: number]: string;
}

类型继承

使用extends,支持多继承:

interface Colorful {
    color: string;
}
 
interface Circle {
    radius: number;
}
 
interface ColorfulCircle extends Colorful, Circle {}
 
const cc: ColorfulCircle = {
    color: "red",
    radius: 42,
};

交集类型 intersection types

使用&运算符获取已知的两个类型的交集。

interface Colorful {
  color: string;
}
interface Circle {
  radius: number;
}
 
type ColorfulCircle = Colorful & Circle;

将两个基本数据类型取交集会得到never

类型继承 VS 交集类型

二者都可以产生更复杂的类型。

前者是在原有的类型的基础上添加可能未有的属性形成新属性,而后者将已有的类型进行组合。

泛型对象类型 Generic Object Types

interface Box<Type> {
  contents: Type;
}

let box: Box<string>;

也可以与泛型函数结合使用:

function setContents<Type>(box: Box<Type>, newContents: Type) {
  box.contents = newContents;
}

除了使用interface,也可以使用type别名定义泛型类型。interface一般用来声明对象类型,而type更灵活,可以组合多种类型:

type OrNull<Type> = Type | null;
type OneOrMany<Type> = Type | Type[];

// type OneOrManyOrNull<Type> = OneOrMany<Type> | null
type OneOrManyOrNull<Type> = OrNull<OneOrMany<Type>>;

// type OneOrManyOrNullStrings = OneOrMany<string> | null
type OneOrManyOrNullStrings = OneOrManyOrNull<string>;

标签:string,04,number,TS,类型,interface,手册,type,name
From: https://www.cnblogs.com/feixianxing/p/typescript-handbook-object-type-optional-readonly-in

相关文章

  • python的websockets库
    安装pipinstallwebsockets分为客户端和服务端两部分  服务端一般与异步的库一起用因为客户端不可能只服务一个客户所以要用异步处理多个客户 以asyncio示例 fromwebsockets.serverimportserveimportwebsocketsimportasyncioasyncdefstart(ws,path):#......
  • Linux 内核参数调整解析:深度优化数据库性能 转载:https://www.toutiao.com/article/73
    系统内核参数配置文件:/etc/sysctl.conf一、参数说明1、关闭IPv6支持net.ipv6.conf.all.disable_ipv6=1net.ipv6.conf.default.disable_ipv6=1作用:关闭对IPv6的支持,减轻系统负担,提高安全性。解析:net.ipv6.conf.all.disable_ipv6:禁用系统中所有网络接口的IPv6。net......
  • Apple开发_Xcode项目中找不到Products文件、无法找到.ipa文件、无法找到打包后的静态
    1、困扰造成的困扰就是找不到.ipa文件了,如果是运行程序用来生成静态库的话,也无法找到.a后或者.framework文件了;编译出的ipa包想直接拿来用,找不到输出的ipa文件。2、解决办法2.1方法一找到项目文件.xcodeproj右击「显示包内容」打开project.pbxproj文件搜索到如下内容:mainGroup=......
  • 谁可以从使用 Amazon Lightsail 进行 VPS 托管中受益?
    文章作者:Libai介绍在当今数字化的环境中,拥有可靠和高效的托管解决方案对于企业和个人来说至关重要。由于其灵活性、可扩展性和成本效益,虚拟专用服务器(VPS)托管已经在市场上获得了巨大的流行。AmazonLightsail 正是市场上备受瞩目的一种 VPS 托管解决方案。亚马逊云科技开发......
  • 【SpringBoot】单元测试报错java.lang.IllegalStateException: Could not load TestCo
    一、运行test类方法时候报错 二、分析原因,发现版本不一致 三、找到pom文件, 把<version>RELEASE</version>注释掉,刷新一下maven依赖 四:修改后,依赖版本一致。 这样,就可以运行了。 ......
  • ubuntu server 22 LTS 安装MySQL8(二进制源码方式)
    原作来源:https://github.com/aminglinux/daily_shell/blob/main/29.sh根据我自己情况稍作修改mysql下载地址:https://downloads.mysql.com/archives/community/ 按照顺序执行逐行执行注意执行过程的提示,报错需处理:tar-xvfmysql-8.0.34-linux-glibc2.17-x86_64.tarsudo......
  • 【Vulnhub 靶场】【Coffee Addicts: 1】【简单-中等】【20210520】
    1、环境介绍靶场介绍:https://www.vulnhub.com/entry/coffee-addicts-1,699/靶场下载:https://download.vulnhub.com/coffeeaddicts/coffeeaddicts.ova靶场难度:简单-中等发布日期:2021年5月20日文件大小:1.3GB靶场作者:BadByte靶场描述:我们的咖啡店被黑客入侵了!!你能修复......
  • [TS手册学习] 02_类型收窄 Narrowing
    TS官方手册:TypeScript:Handbook-TheTypeScriptHandbook(typescriptlang.org)一个变量如果声明为联合类型,而后续操作需要针对其具体的单一类型做不同处理,这个过程就叫做类型收窄(Narrowing)。常见的做法或情形有以下:typeof类型保护(typeguards)typeof是JS中的操作符,......
  • day1数组理论基础,704. 二分查找,27. 移除元素
    数组理论基础,704.二分查找,27.移除元素1数组理论基础1.1数组概念定义:存放在连续内存空间上的相同类型数据的集合。特点:1.数组中数据类型相同2.数组所占空间连续1.2数组创建2704.二分查找给定一个n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数......
  • 代码大全-04
    单一职责原则的重要性:书中强调了单一职责原则,即一个类应该有且仅有一个引起它变化的原因。这让我意识到编写高质量的类不仅仅是关于功能的实现,更重要的是要考虑类的职责是否清晰明确,这样才能提高代码的可维护性和可理解性。封装性的作用:封装性是另一个重要的概念,它可以帮助我们隐......