TypeScript里的自定义类型用法
生活随笔
收集整理的這篇文章主要介紹了
TypeScript里的自定义类型用法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
新建一個index.ts:
type NumGenerator = (input: number) => number;function myFunc(numGenerator: NumGenerator | undefined) {// Object is possibly 'undefined'.(2532)// Cannot invoke an object which is possibly 'undefined'.(2722)const num1 = numGenerator(1); // Errorconst num2 = numGenerator!(2); //OKreturn {num_1: num1,num_2: num2} }const jerry: NumGenerator = (input) => input + 1;console.log(jerry(1)); console.log(jerry(2));export class TestClass{constructor(){console.log(jerry(1));console.log(jerry(2));console.log(myFunc(jerry));} }使用type定義了一個新的類型,代表一個函數,擁有一個輸入參數,類型為number,返回類型也為number.
接著可以像使用普通類型一樣的方式,使用該類型定義自己的函數變量。
最后的輸出:
總結
以上是生活随笔為你收集整理的TypeScript里的自定义类型用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 第五人格共研服激活码怎么得?第五人格共研
- 下一篇: 在StackBlitz上进行rxjs编程