@@ -296,74 +296,3 @@ export function defineComponent(options: unknown) {
296296}
297297
298298```
299- 300- 301- 联合类型(Union Types),表示一个值可以是几种类型之一。 我们用竖线 | 分隔每个类型,所以 number | string | boolean表示一个值可以是 number, string,或 boolean
302- 303- ``` js
304- type arg = string | number | boolean
305- const foo = (arg: arg): any => {
306- console .log (arg)
307- }
308- foo (1 )
309- foo (' 2' )
310- foo (true )
311- ```
312- 313- ### 函数重载
314- 315- 函数重载(Function Overloading), 允许创建数项名称相同但输入输出类型或个数不同的子程序,可以简单理解为一个函数可以执行多项任务的能力
316- 317- 例我们有一个` add ` 函数,它可以接收` string ` 类型的参数进行拼接,也可以接收` number ` 类型的参数进行相加
318- 319- ``` js
320- function add (arg1 : string , arg2 : string ): string
321- function add (arg1: number, arg2: number): number
322- 323- // 实现
324- function add <T,U>(arg1: T, arg2: U) {
325- // 在实现上我们要注意严格判断两个参数的类型是否相等,而不能简单的写一个 arg1 + arg2
326- if (typeof arg1 === ' string' && typeof arg2 === ' string' ) {
327- return arg1 + arg2
328- } else if (typeof arg1 === ' number' && typeof arg2 === ' number' ) {
329- return arg1 + arg2
330- }
331- }
332- 333- add (1 , 2 ) // 3
334- add (' 1' ,' 2' ) // '12'
335- ```
336- 337- ### 总结
338- 339- 通过本篇文章,相信大家对` Typescript ` 不会再感到陌生了
340- 341- 下面我们来看看在` Vue ` 源码` Typescript ` 是如何书写的,这里我们以` defineComponent ` 函数为例,大家可以通过这个实例,再结合文章的内容,去理解,加深` Typescript ` 的认识
342- 343- ``` js
344- // overload 1: direct setup function
345- export function defineComponent<Props, RawBindings = object>(
346- setup : (
347- props: Readonly< Props> ,
348- ctx: SetupContext
349- ) => RawBindings | RenderFunction
350- ): {
351- new (): ComponentPublicInstance<
352- Props,
353- RawBindings,
354- {},
355- {},
356- {},
357- // public props
358- VNodeProps & Props
359- >
360- } & FunctionalComponent< Props>
361- 362- // defineComponent一共有四个重载,这里省略三个
363- 364- // implementation, close to no-op
365- export function defineComponent (options : unknown ) {
366- return isFunction (options) ? { setup: options } : options
367- }
368- 369- ```
0 commit comments