关于typescript的类型定义

// number类型

const n: number = 1;

// string类型

const s: string = '';

// boolean类型

const b: boolean = true;

// array类型

const arr: string[] = [];

// tuple类型

const tuple: [boolean, string] = [true, 'true'];

// enum类型

enum Color {
  red = 'red',
  blue = 'blue ',
}
const  c: Color = Color.red;

// any类型

// any 类型不会做做检查 也不会有提示
let a: any = 1;
a = 's';

// unknown类型

// unknown类型是会做检查的
let unKnownEle: unknown;
unKnownEle = "马松松"
unKnownEle = 12345;
unKnownEle.toFixed(); // 会报错 类型“unknown”上不存在属性“toFixed”。

// 函数

const func1: (name: string, old: number) => string = (name, old) => {
	return `${name}:${old + 1}`;
};

const func2 = (name: string, old?: number) => {
	if (old) {
		return old;
	} else {
		return name;
	}
};

// void不是类型 只做函数返回值 当函数没有返回值是使用
const func3: (name: string) => void = (name) => {
	console.log(name);
};

// 当函数永远不返回时为never
const func4: (name: string) => never = (name: string) => {
	while (true) {
		console.log(name);
	}
};

// 函数的重载

function Test(): string;
function Test(name: string, old: number): string;
function Test(name?: string, old?: number) {
	if (name && old) {
		return `${name}:${old}`;
	}
	return 'none';
}

Test(); // 'none'
Test('zwq'); // 没有需要 1 参数的重载,但存在需要 0 或 2 参数的重载
Test('zwq', 29); // 'zwq:29'

interface A {
	(): string;
	(name: string, old: number): string;
}

const a: A = (name?: string, old?: number) => {
	if (name && old) {
		return `${name}:${old}`;
	}
	return 'none';
};

a(); // 'none'
a('zwq'); // 没有需要 1 参数的重载,但存在需要 0 或 2 参数的重载
a('zwq', 29); // 'zwq:29'

// 内置类型的使用

const a = {
	name: 'zwq',
	old: 29,
	email: '888888@qq.com',
	address: '****路',
	hobby: '唱歌',
};

// typeof 获取值的类型
type A = typeof a;
// type A = {
// 	name: string;
// 	old: number;
// 	email: string;
// 	address: string;
// 	hobby: string;
// };

// keyof 类型的key
type B = keyof A;
// type B = "name" | "old" | "email" | "address" | "hobby";

// Record 映射
type C = Record<B, string>;
// type C = {
// 	name: string;
// 	old: string;
// 	email: string;
// 	address: string;
// 	hobby: string;
// };

// Exclude 排除
type D = Exclude<B, 'hobby' | 'address' | 'email'>;
// type D = "name" | "old";

// Pick 挑拣属性
type E = Pick<A, 'hobby' | 'address' | 'email'>;
// type E = {
// 	hobby: string;
// 	address: string;
// 	email: string;
// };

//  Omit 忽略属性
type F = Omit<A, 'name' | 'old'>;
// type F = {
// 	hobby: string;
// 	address: string;
// 	email: string;
// };

// Extract 交集
type G = Extract<B, 'hobby' | 'aaa'>;
// type G = "hobby";

// infer推断

// 通过typeof可以回去值的类型以及keyof获取interface的key
// 如何获取函数的参数的类型呢?
// infer类型推断 就相当与函数的args占位符

type VariadicFn<A extends any[]> = (...args: A) => any;
type ArgsType<T> = T extends VariadicFn<infer A> ? A : never;

type Fn = (a: number, b: string) => string;
type Fn2Args = ArgsType<Fn>; // [number, string]

// interface

// interface 形式与object一样相当于type的子集
interface A {
	name: string;
	old: number;
	[key: string]: any; // 动态扩展使用
}

const a: A = {
	name: 'zwq',
	old: 1,
};
a.hobby = '唱歌';

// 接口继承
interface B extends A {
    hobby: string;
}
const b: B = {
	name: 'zwq',
	old: 1,
	hobby: '唱歌',
};

// 类型断言

interface A {
	name: string;
	old: number;
	hobby: string;
}

// 接口继承
interface B extends Omit<A, 'hobby'> {
	addr: string;
}

const a: A = {
	name: 'zzz',
	old: 29,
	hobby: 'sing',
};

const b: B = {
	name: 'zzz',
	old: 29,
	addr: '****',
};

const userInfo = (mes: A | B) => {
	if ((mes as B).addr) {
		const b = mes as B;
		console.log(b.addr);
	}
	if ((mes as A).hobby) {
		const a = mes as A;
		console.log(a.hobby);
	}
};

参考文档:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
DefinitelyTyped 包含大量的高质量的 TypeScript 类型定义。 包括: Ace Cloud9 Editor (by Diullei Gomes) AmCharts (by Covobonomo) AngularJS (by Diego Vilar) (wiki) Arbiter (by Arash Shakery) async (by Boris Yankov) Backbone.js (by Boris Yankov) Backbone Relational (by Eirik Hoem) Bootbox (by Vincent Bortone) Bootstrap (by Boris Yankov) bootstrap-notify (by Blake Niemyjski) bootstrap.datepicker (by Boris Yankov) Box2DWeb (by Josh Baldwin) Breeze (by Boris Yankov) CasperJS (by Jed Hunsaker) Cheerio (by Bret Little) Chosen (by Boris Yankov) Chrome (by Matthew Kimber) CodeMirror (by François de Campredon) Commander (by Marcelo Dezem) d3.js (from TypeScript samples) domo (by Steve Fenton) dust (by Marcelo Dezem) EaselJS (by Pedro Ferreira) ember.js (by Boris Yankov) EpicEditor (by Boris Yankov) expect.js (by Teppei Sato) Express (by Boris Yankov) Ext JS (by Brian Kotek) Fabric.js (by Oliver Klemencic) Fancybox (by Boris Yankov) File API: Directories and System (by Kon) File API: Writer (by Kon) Finite State Machine (by Boris Yankov) Firebase (by Vincent Bortone) FlexSlider (by Diullei Gomes) Foundation (by Boris Yankov) FPSMeter (by Aaron Lampros) FullCalendar (by Neil Stalker) Gamepad (by Kon) glDatePicker (by Dániel Tar) GreenSock Animation Platform (GSAP) (by Robert S.) Grunt JS (by Basarat Ali Syed) Google API Client (by Frank M) Google App Engine Channel API (by vvakame) GoogleMaps (by Esben Nepper) Google Geolocation (by Vincent Bortone) Google Page Speed Online API (by Frank M) Google Translate API (by Frank M) Google Url Shortener (by Frank M) Hammer.js (by Boris Yankov) Handlebars (by Boris Yankov) Highcharts (by damianog) History.js (by Boris Yankov) Humane.js (by John Vrbanac) i18next (by Maarten Docter) iCheck (by Dániel Tar) Impress.js (by Boris Yankov) iScroll (by Boris Yankov) jake (by Kon) Jasmine (by Boris Yankov) jQRangeSlider (by Dániel Tar) jQuery (from TypeScript samples) jQuery Mobile (by Boris Yankov) jQuery UI (by Boris Yankov) jQuery.autosize (by Jack Moore) jQuery.BBQ (by Adam R. Smith) jQuery.contextMenu (by Natan Vivo) jQuery.clientSideLogging (by Diullei Gomes) jQuery.Colorbox (by Gidon Junge) jQuery.Cookie (by Roy Goode) jQuery.Cycle (by François Guillot) jQuery.dataTables (by Armin Sander) jQuery.dynatree (by François de Campredon) jQuery.Flot (by Matt Burland) jQuery.form (by François Guillot) jQuery.Globalize (by Boris Yankov) jQuery.jNotify (by James Curran) jQuery.noty (by Aaron King) jQuery.pickadate (by Theodore Brown) jQuery.scrollTo (by Neil Stalker) jQuery.simplePagination (by Natan Vivo) jQuery.timeago (by François Guillot) jQuery.Timepicker (by Anwar Javed) jQuery.TinyCarousel (by Christiaan Rakowski) jQuery.TinyScrollbar (by Christiaan Rakowski) jQuery.Transit (by MrBigDog2U) jQuery.Validation (by Boris Yankov) jQuery.Watermark (by Anwar Javed) jScrollPane (by Dániel Tar) JSDeferred (by Daisuke Mino) JSONEditorOnline (by Vincent Bortone) jStorage (by Danil Flores) JWPlayer (by Martin Duparc) KeyboardJS (by Vincent Bortone) Knockback (by Marcel Binot) Knockout.js (by Boris Yankov) Knockout.Mapping (by Boris Yankov) Knockout.Postbox (by Judah Gabriel) Knockout.Validation (by Dan Ludwig) Knockout.Viewmodel (by Oisin Grehan) ko.editables (by Oisin Grehan) KoLite (by Boris Yankov) Leaflet (by Vladimir) Libxmljs (by François de Campredon) ladda (by Danil Flores) linq.js (by Marcin Najder) Livestamp.js (by Vincent Bortone) Marked (by William Orr) Modernizr (by Boris Yankov and Theodore Brown) Moment.js (by Michael Lakerveld) Mousetrap (by Dániel Tar) Mustache.js (by Boris Yankov) Node.js (from TypeScript samples) node_redis (by Boris Yankov) node_zeromq (by Dave McKeown) node-sqlserver (by Boris Yankov) Numeral.js (by Vincent Bortone) PhantomJS (by Jed Hunsaker) PhoneGap (by Boris Yankov) Platform (by Jake Hickman) PouchDB (by Bill Sears) PreloadJS (by Pedro Ferreira) QUnit (by Diullei Gomes) Restify (by Bret Little) Rx.js (by gsino) Raphael (by CheCoxshall) Restangular (by Boris Yankov) require.js (by Josh Baldwin) Sammy.js (by Boris Yankov) Select2 (by Boris Yankov) Sencha Touch (by Brian Kotek) SharePoint (by Stanislav Vyshchepan and Andrey Markeev) SignalR (by Boris Yankov) Sinon (by William Sears) socket.io (by William Orr) SockJS (by Emil Ivanov) SoundJS (by Pedro Ferreira) Spin (by Boris Yankov) Store.js (by Vincent Bortone) Sugar (by Josh Baldwin) SwipeView (by Boris Yankov) Tags Manager (by Vincent Bortone) Teechart (by Steema) three.js (by Kon) Toastr (by Boris Yankov) trunk8 (by Blake Niemyjski) TweenJS (by Pedro Ferreira) tween.js (by Adam R. Smith) twitter-bootstrap-wizard (by Blake Niemyjski) Ubuntu Unity Web API (by John Vrbanac) Underscore.js (by Boris Yankov) Underscore.js (Typed) (by Josh Baldwin) Underscore-ko.js (by Maurits Elbers) Viewporter (by Boris Yankov) Vimeo (by Daz Wilkin) WebRTC (by Ken Smith) YouTube (by Daz Wilkin) YouTube Analytics API (by Frank M) YouTube Data API (by Frank M) Zepto.js (by Josh Baldwin) Zynga Scroller (by Boris Yankov) ZeroClipboard (by Eric J. Smith)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值