TypeScript里的自定义类型用法

98 阅读1分钟

新建一个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); // Error
    const num2 = numGenerator!(2); //OK
    return {
        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.

接着可以像使用普通类型一样的方式,使用该类型定义自己的函数变量。

最后的输出:

在这里插入图片描述