10 个关于 TypeScript 的小技巧
英文 | https://www.sangle7.com/
1、 TypeScript 和 DOM
const textEl = document.querySelector('inpot');
console.log(textEl.value);
// ? Property 'value' does not exist on type 'Element'.
interface HTMLElementTagNameMap {
a: HTMLAnchorElement;
abbr: HTMLElement;
address: HTMLElement;
applet: HTMLAppletElement;
area: HTMLAreaElement;
article: HTMLElement;
/* ... */
input: HTMLInputElement;
/* ... */
}
textEl.addEventListener('click', (e) => {
console.log(e.clientX);
});
2、期望泛型
document.querySelector('input.action')
textEl = document.querySelector < HTMLInputElement > 'input.action';
console.log(textEl.value);
// ? 'value' is available because we've instructed TS
// about the type the 'querySelector' function works with.
3、“我们真的找到了吗?”
{
"compilerOptions": {
"strictNullChecks": true
}
}
const textEl = document.querySelector('input');
console.log(textEl!.value);
// ? with "!" we assure TypeScript
// that 'textEl' is not null/undefined
5、当迁移到 TS…
// tslint:disable
let mything = 2;
mything = 'hi';
// ? Type '"hi"' is not assignable to type 'number'
mything = 'hi' as any;
// ? if you say "any", TypeScript says ¯\_(ツ)_/¯
6、更多限制
function fn(param) {
console.log(param);
}
{
"compilerOptions": {
"noImplicitAny": true
}
}
{
"rules": {
"typedef": [
true,
"call-signature"
]
}
}
7、类型保护
type BookId = number | string;
function returnFormatterId(id: BookId) {
return id.toUpperCase();
// ? 'toUpperCase' does not exist on type 'number'.
}
function returnFormatterId(id: BookId) {
if (typeof id === 'string') {
// we've made sure it's a string:
return id.toUpperCase(); // so it's ?
}
// ? TS also understands that it
// has to be a number here:
return id.toFixed(2)
}
8、再谈泛型
interface Bookmark {
id: string;
}
class BookmarksService {
items: Bookmark[] = [];
}
interface Movie {
id: string;
name: string;
}
class SearchPageComponent {
movie: Movie;
constructor(private bs: BookmarksService) {}
getFirstMovie() {
// ? types are not assignable
this.movie = this.bs.items[0];
// ? so you have to manually assert type:
this.movie = this.bs.items[0] as Movie;
}
getSecondMovie() {
this.movie = this.bs.items[1] as Movie;
}
}
class BookmarksService
{ items: T[] = [];
}
class BookmarksService
{ items: T[] = [];
}
class SearchPageComponent {
movie: Movie;
constructor(private bs: BookmarksService
) {} getFirstMovie() {
this.movie = this.bs.items[0]; // ?
}
getSecondMovie() {
this.movie = this.bs.items[1]; // ?
}
}
class BookmarksService
{ items: T[] = [];
}
const bs = new BookmarksService();
// I don't have to provide the type for the generic now
// - in that case 'bs' will be of that default type 'Bookmark'
9、路由参数
export interface DashboardRouteParams {
countryId: string;
deviceId: string;
}
const routes: Routes = [{
path: 'country/:countryId/device/:deviceId/dashboard'
}]
10、根据 API 响应创建 Interface
http://www.json2ts.com http://www.jsontots.com
https://app.quicktype.io/
评论