typescript 技巧
These are the 3 tips I found pretty handy while working with Typescript:
这些是我在使用Typescript时发现非常方便的3个技巧:
- Eliminating the need to import interfaces 消除了导入接口的需要
- Making all interface properties optional 使所有接口属性为可选
- Stop throwing me error, I know what I'm doing 别把我丢给我,我知道我在做什么
Though I discovered these while working with Angular application, but all tips are not Angular specific, it's just Typescript.
尽管我在使用Angular应用程序时发现了这些,但是所有技巧并非特定于Angular,而只是Typescript。
消除了导入接口的需要 ( Eliminating the need to import interfaces )
I like interfaces. However, I don't like to import them everytime. Although Visual Studio Code has auto-import feature, I don't like my source files been "polluted" by multiple lines of imports - just for the purpose of strong typing.
我喜欢界面。 但是,我不喜欢每次都导入它们。 尽管Visual Studio Code具有自动导入功能,但我不希望源文件被多行导入“污染”,仅出于强类型键入的目的。
This is how we do it normally.
这就是我们通常的做法。
// api.model.ts
export interface Customer {
id: number;
name: string;
}
export interface User {
id: number;
isActive: boolean;
}
// using the interfaces
import { Customer, User } from './api.model'; // this line will grow longer if there's more interfaces used
export class MyComponent {
cust: Customer;
}
解决方案1:使用名称空间 (Solution 1: Using namespace)
By using namespace, we can eliminate the needs to import interfaces files.
通过使用命名空间,我们可以消除导入接口文件的需要 。
// api.model.ts
namespace ApiModel {
export interface Customer {
id: number;
name: string;
}
export interface User {
id: number;
isActive: boolean;
}
}
// using the interfaces
export class MyComponent {
cust: ApiModel.Customer;
}
Nice right? Using namespace also help you to better organize & group the interfaces. Please note that you can split the namespace across many files.
不错吧? 使用名称空间还可以帮助您更好地组织和分组接口。 请注意,您可以将命名空间拆分为多个文件。
Let's say you have another file called api.v2.model.ts
. You add in new interfaces, but you want to use the same namespace.
假设您还有另一个名为api.v2.model.ts
文件。 您添加了新的接口,但是要使用相同的名称空间。
// api.v2.model.ts
namespace ApiModel {
export interface Order {
id: number;
total: number;
}
}
You can definitely do so. To use the newly created interface, just use them like the previous example.
您绝对可以这样做。 要使用新创建的界面,只需像前面的示例一样使用它们即可。
// using the interfaces with same namespaces but different files
export class MyComponent {
cust: ApiModel.Customer;
order: ApiModel.Order;
}
Here is the detail documentation on Typescript namespacing.
这是有关Typescript名称空间的详细文档 。
解决方案2:使用d文件 (Solution 2: Using d file)
The other way to eliminate import is to create a typescirpt file end with .d.ts
. "d" stands for declaration file in Typescript (more explanation here).
消除进口的另一种方法是创建一个typescirpt文件结束.d.ts
。 “ d”代表Typescript中的声明文件( 此处有更多说明)。
// api.model.d.ts
// you don't need to export the interface in d file
interface Customer {
id: number;
name: string;
}
Use it as normal without the need to import it.
无需导入即可照常使用它。
// using the interfaces of d file
export class MyComponent {
cust: Customer;
}
I recommend solution 1 over solution 2 because:
我建议解决方案1胜过解决方案2,因为:
- d file usually use for external, 3rd party declaration d文件通常用于外部第三方声明
- namespace allow us to better organize the files 命名空间使我们可以更好地组织文件
使所有接口属性为可选 ( Making all interface properties optional )
It's quite common where you will use same interface for CRUD. Let's say you have a customer interface, during creation, all fields are mandatory, but during update, all fields are optional. Do you need to create two interfaces to handle this scenario?
在CRUD中使用相同的接口是很常见的。 假设您有一个客户界面,在创建期间,所有字段都是必填字段,但在更新期间,所有字段都是可选字段。 您是否需要创建两个接口来处理这种情况?
Here is the interface
这是界面
// api.model.ts
export interface Customer {
id: number;
name: string;
age: number;
}
解决方案:使用部分 (Solution: Use Partial)
Partial
is a type to make properties an object optional. The declaration is included in the default d file lib.es5.d.ts
.
Partial
是一种使属性成为对象可选的类型。 该声明包含在默认的d文件lib.es5.d.ts
。
// lib.es5.d.ts
type Partial<T> = {
[P in keyof T]?: T[P];
};
How can we use that? Look at the code below:
我们如何使用它? 看下面的代码:
// using the interface but make all fields optional
import { Customer } from './api.model';
export class MyComponent {
cust: Partial<Customer>; /
ngOninit() {
this.cust = { name: 'jane' }; // no error throw because all fields are optional
}
}
If you don't find Partial
declaration, you may create a d file yourself (e.g. util.d.ts) and copy the code above into it.
如果找不到Partial
声明,则可以自己创建广告文件(例如util.d.ts),并将上面的代码复制到其中。
For more advance type usage of Typescript, you can read here.
有关Typescript的更多高级类型用法,您可以在此处阅读。
别把我丢给我,我知道我在做什么 ( Stop throwing me error, I know what I'm doing )
As a Javascript turns Typescript developer, one might find Typescript error is annoying sometimes. In some scenario, you just want to tell Typescript, "hey, I know what I am doing, please leave me alone.".
随着Javascript变成Typescript开发人员,人们有时会发现Typescript错误很烦人。 在某些情况下,您只想告诉Typescript:“嘿,我知道我在做什么,请别理我。”
解决方案:使用@ts-ignore
注释 (Solution: Use @ts-ignore
comment)
From Typescript version 2.6 onwards, you can do so by using comment @ts-ignore
to suppress error.
从Typescript 2.6版开始,您可以使用comment @ts-ignore
来抑制错误。
For example, Typescript will throw error "Unreachable code detected" in this following code:
例如,Typescript将在以下代码中引发错误“检测到无法访问的代码”:
if (false) {
console.log('x');
}
You can suppress that by using comment @ts-ignore
您可以通过使用@ts-ignore
来禁止显示
if (false) {
// @ts-ignore
console.log('x');
}
Find out more details here: Typescript 2.6 release
在此处了解更多详细信息: Typescript 2.6版本
Of course, I will suggest you to always try fix the error before ignoring it!
当然,我建议您在忽略该错误之前总是尝试修复该错误!
摘要 ( Summary )
Typescript is good for your (code) health. It has pretty decent documentation. I like the fact that they have comprehensive What's new
documentation for every release. It's an open source project in Github if you would like to contribute. The longer I work with Typescript, the more I love it and appreciate it.
打字稿对您(代码)的健康有益。 它有相当不错的文档 。 我喜欢这样的事实,他们为每个版本提供了全面What's new
文档。 如果您愿意做出贡献,这是Github中的一个开源项目 。 我使用Typescript的时间越长,我就越喜欢它并欣赏它。
That's it, happy coding!
就是这样,快乐的编码!
翻译自: https://scotch.io/tutorials/3-useful-typescript-tips-for-angular
typescript 技巧