2-1-5 TS日常类型

基础类型

string,  number,  boolean,  null,  undefined

数组类型

Array<T>,T代表数组中的元素类型。

any/unkown/noImplictAny

let obj: any = { x: 0 };
// 后续都不会被检查.
// `any`屏蔽了所有类型检查,相当于你相信你对程序的理解是高于TS的
obj.foo();
obj(); // 运行时会报错
obj.bar = 100;
obj = "hello";
const n: number = obj;

*Implict* : 隐式

*explict* : 显式

配置项:noImplicitAny,当你不为变量声明类型时,如果noImplicitAny=false,那么它是any。如果noImplicitAny=true呢? ——报错

tsconfig.json

{
	"compilerOptions": {
		"noImplicitAny": true
	}
}

unknown

let value: unknown;

value = true;             // OK
value = 42;               // OK
value = "Hello World";    // OK

let value3: boolean = value; // Error

类型标注

`:` 用于类型标注。

let myName: string = "Alice";

let myName = "Alice" // ts 会 类型推导 myName的类型 为 string

函数

// greet : string -> number (Haskell)
function greet(name: string) : number {
  console.log("Hello, " + name.toUpperCase() + "!!");
}

greet(42) // Error
let x : string = greet("omg") // Error

匿名函数的类型

const names = ["Alice", "Bob", "Eve"];
// Array<string>

names.forEach(function (s) {
  console.log(s.toUpperCase());
});

names.forEach((s) => {
  console.log(s.toUpperCase());
});

知识点:contexture typing(根据上下文猜测匿名函数参数的类型)。

函数可选参数:

function print(arg1 : string, arg2 ? : string) {
    console.log(arg1, arg2)
}

print("Hello", "World")
print("Hello")

对象类型

对象如果描述了类型也需要严格执行。

const pt : {
    x  : number,
    y : number
} = {x : 100, y : 100}

pt.z = 10000 // Error

可选项:

function printName(obj : {first : string, last ? string}) {
    
}

printName({first :'Bob'})
printName({first :'Alice', last : "Alisson"})

`?` 表达式

?代表可能是undefined,但是安全很多。

const o : {
    a : string,
    b ? : {
        c : string
    }
} = {a : "1"}

console.log(o.b.c) // Error


console.log(o.b?.c) // undefined

o.b?.c = "Hello" // Error

联合

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");
// Error
printId({ myID: 22342 });

联合类型只能使用两个类型的公共操作。

function printId(id: number | string) {
  console.log(id.toUpperCase());
  // Property 'toUpperCase' does not exist on type 'string | number'.
}

Typescript会针对联合类型做排除法:

function printID(id : number | string) {
    if(typeof id === 'number') {
        console.log(id)
        return
    }
    console.log(id.toUpperCase())
}

这个也叫做类型窄化技术

类型别名

type Point = {
  x: number;
  y: number;
};


function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}

printCoord({ x: 100, y: 100 });

类型别名也可以使用联合:

type ID = number | string

注意,别名只是别名,例如:

let x : ID = 100
// typeof x === 'number'

当然别名可以和它代表的类型一起工作(因为别名不是创建了新的类型):

let id : ID = "abc"
id = 456 // OK

接口

interface Point {
  x: number;
  y: number;
}

function printCoord(pt: Point) {
  console.log("The coordinate's x value is " + pt.x);
  console.log("The coordinate's y value is " + pt.y);
}

printCoord({ x: 100, y: 100 });

1

接口的声明合并(Declaration Merging)

interface Box {
  height: number;
  width: number;
}
interface Box {
  scale: number;
}
let box: Box = { height: 5, width: 6, scale: 10 };

 特别说明:你也可以把这种能力看做是向接口中添加成员的能力。

类型断言 (assertion)

有时候Ts对类型的理解没有你多,这个时候你就需要用类型断言:

const myCanvas = 
    // HTMLElement
    document.getElementById("main_canvas") as HTMLCanvasElement;

通常TS会接收“说的通”的类型断言。

比如: 父类 as 子类, 联合 as 单个。

但是有的类型断言TS会拒绝,比如:

const x = 'hello' as number

TS会报一个这样的错误:Conversion of type 'string' to type 'number' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

当然有时候你可以用any as T来“欺骗”TS,或者说蒙混过关:

const a = (expr as unknown) as T;

字面类型

对于常量,在TS中实际上是Literal Type(字面值类型)。

比如:

const someStr = "abc"
// someStr的类型是 "abc",它的值只能是abc

const foo = 1
// foo 的类型是1(而不是整数)。

// 当然这只是ts的理解,如果用typeof 操作符
// typeof someStr // 'string'
// typeof foo // 1

// 对于let
let foo = 1 // foo : number

可以用字面类型来约束一些特殊的函数,比如:

function compare(a: string, b: string): -1 | 0 | 1 {
  return a === b ? 0 : a > b ? 1 : -1;
}

当然下面是一个更加贴近真实场景的例子:

interface Options {
  width: number;
}
function configure(x: Options | "auto") {
  // ...
}
configure({ width: 100 });
configure("auto");
configure("automatic"); // Argument of type '"automatic"' is not assignable to parameter of type 'Options | "auto"'.

字面类型的一个坑:

function handleRequest(url : string, method : "GET" | "POST") {
    // do...
}

const req = { url: "https://example.com", method: "GET" };
handleRequest(req.url, req.method);
// Error : Argument of type 'string' is not assignable to parameter of type '"GET" | "POST"'.

// 1
const req = { url: "https://example.com", method: "GET" as "GET" };

// 2 
handleRequest(req.url, req.method as "GET");

// 3 
const req = { url: "https://example.com", method: "GET" } as const

null / undefined

null和undefined是Javascript的两种基础类型(Primitive type),它们描述的是不同的行为:

- undefined是一个没有被分配值的变量

- null是一个被人为分配的空值

Typescript有一个配置项,叫做`strictNullChecks` ,这个配置项设置为`on` 的时候,在使用有可能是null的值前,你需要显式的检查。

tsconfig.json

{
	"compilerOptions": {
		"noImplicitAny": true,
		"strictNullChecks": true
	}
}

strictNullChecks 设置为 true 时,需要对代码做显示的检查

原则上尽可能的在编译时报错,不要在运行时报错

function doSomething(x: string | null) {
  if (x === null) {
    // do nothing
  } else {
    console.log("Hello, " + x.toUpperCase());
  }
}

另外, 可以用`!` 操作符,来断言某个值不是空值:

function doSomething(x: string | null) {
  console.log("Hello, " + x!.toUpperCase());
}

枚举类型

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}

console.log(Direction.Up)  // 1

console.log(Direction[Direction.Up])  // Up 

上面的含义, Down = 2, Left = 3, Right = 4

枚举类型最后会被翻译成整数,因此枚举的很多性质和整数相似。比如Down.toString()会返回2,而不是`Down` 。正因为如此,枚举类型的效率很高。

当然如果你想用字符串类的枚举(个人觉得没有必要),就需要显示的为每一项赋值:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT",
}

当然也可以混合,不过非但没有意义,而且会减少代码的可读性:

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES",
}

在运行时,Enum会被解释成对象,Enum的每项会被解释成常数。

下面这个例子可以很好的证明。

enum E {
  X,
  Y,
  Z,
}

function f(obj: { X: number }) {
  return obj.X;
}

f(E)

可以用下面这个语法提取Enum中的字符串,这个也叫Reverse Mapping。

E[E.X] // X

1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
IEC/TS 61000-1-2是国际电工委员会(IEC)制定的一项技术规范,标准编号为61000-1-2。该技术规范的名称是"电磁兼容性(EMC)-第1-2部分:一般原则-电压波动、闪烁和电网颗粒性扰动"。 IEC/TS 61000-1-2是电磁兼容性(EMC)测试中的一个重要标准。它主要关注电力系统中发生的电压波动、闪烁以及电网颗粒性扰动的测量和评估。该标准的目的是保证各种电器设备和系统能够在电力系统的电压波动和其他电磁干扰条件下正常工作。 该技术规范规定了测量和评估电压波动和闪烁的方法、技术指标和评估方法。它要求参与电力系统的各种设备和系统在持续和间歇的电压波动、闪烁和电力网络颗粒性扰动下能够正常运行,并且不会对电力系统产生负面影响。 IEC/TS 61000-1-2标准的主要应用领域是电力系统的设计、安装和运行。该标准适用于各种环境条件下的电力系统,包括低压和高压电力网络。它为电力系统的各种参与设备和系统提供了指导和要求,确保其能够与电力系统的其他部分协调工作,维持电力系统的稳定性和可靠性。 总的来说,IEC/TS 61000-1-2是电磁兼容性测试中的一项重要技术规范,关注电力系统中的电压波动、闪烁和电网颗粒性扰动的测量和评估。它的应用范围广泛,对于电力系统的设计和运行至关重要,能够确保各种设备和系统在电力系统条件下正常工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值