首页 > 其他分享 >兼收并蓄 TypeScript - 类: function

兼收并蓄 TypeScript - 类: function

时间:2024-09-20 12:13:22浏览次数:1  
标签:function TypeScript string number 兼收并蓄 webabcd p1 hello

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

兼收并蓄 TypeScript - 类: function

示例如下:

class\function.ts

{
    // 定义函数时要指定参数的类型和返回值的类型,无返回值时可以用 void 表示
    function f1(x:number, y:number):number {
        return x + y;
    }
    function f2(x:string, y:string):void {
        
    }
    // 返回值的类型也可以推导出来
    function f3(x:number, y:number) {
        return x * y
    }
    // 允许在函数参数列表和调用时使用尾随逗号(这个逗号没有实际意义,只是为了可以方便地添加或删除参数)
    function f4(x:number, y:number, ) {

    }
    f4(1, 2)
    f4(1, 2, )


    // 参数默认值
    function a(p1:string, p2:string="webabcd"):string {
        return `${p1} ${p2}`;
    }
    console.log(`${a("hello", "wanglei")}, ${a("hello")}`);
    // hello wanglei, hello webabcd


    // 可选参数
    function b(p1:string, p2?:string):string {
        return `${p1} ${p2}`;
    }
    console.log(`${b("hello", "wanglei")}, ${b("hello")}`);
    // hello wanglei, hello undefined


    // 通过 ... 定义剩余参数,用于接收指定类型的可变数量的参数
    function c(p1:string, ...values:string[]) {
        let result = "";
        for (let i = 0; i < values.length; i++) {
            result += values[i];
        }
        return `${p1} ${result}`;
    }
    console.log(`${c("1", "2", "3", "4", "5")}`);
    // 1 2345
}

{
    // 箭头函数(lambda 表达式)
    let a = ():string => "hello"; // 无参数,通过一行表达式实现返回值
    let b = (p1:string, p2:string):string => `${p1} ${p2}`; // 多个参数,通过一行表达式实现返回值
    let c = (p1:string, p2:string):string => { // 通过多行表达式实现返回值(加上大括号即可)
        let result = `${p1} ${p2}`;
        return result;
    };
    let d = function (p1:string, p2:string):string { // 经典的 function 方式
        let result = `${p1} ${p2}`;
        return result;
    };
    console.log(`${a()}, ${b("hello", "webabcd")}, ${c("hello", "webabcd")}, ${d("hello", "webabcd")}`);
    // hello, hello webabcd, hello webabcd, hello webabcd
}

{
    // 通过函数声明(Function Declaration)的方式定义函数
    function f1(x: number, y: number): number {
        return x + y;
    }

    // 通过函数表达式(Function Expression)的方式定义函数
    let f2 = function (x: number, y: number): number {
        return x + y;
    };

    // 上面的函数 f2 的类型是推导出来的,如果写全的话就像下面这样
    // 这里的 => 不是 es6 中的箭头函数
    // 这里的 => 是用来定义函数类型的,左边是输入类型,需要用括号括起来,右边是输出类型
    let f3: (x: number, y: number) => number = function (x: number, y: number): number {
        return x + y;
    };
}

{
    // 通过接口定义函数的形状
    interface MyInterface {
        (p1: string, p2: string): string;
    }
    let a: MyInterface = function(p1: string, p2: string) {
        return `${p1} ${p2}`;
    }
    console.log(a("hello", "webabcd")); // hello webabcd
}

{
    // es6 是不支持函数重载的
    // typescript 可以通过如下方式支持函数重载
    function myFunc(x: number): number;
    function myFunc(x: string): string;
    function myFunc(x: number | string): number | string | void {
        if (typeof x === 'number') {
            return x * 2;
        } else if (typeof x === 'string') {
            return `hello ${x}`;
        } else {
            // void
        }
    }
    console.log(myFunc(100), myFunc("webabcd")); // 200 hello webabcd
}

源码 https://github.com/webabcd/TypeScriptDemo
作者 webabcd

标签:function,TypeScript,string,number,兼收并蓄,webabcd,p1,hello
From: https://www.cnblogs.com/webabcd/p/18422251/typescript_class_function

相关文章

  • 兼收并蓄 TypeScript - 类: interface
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-类:interface示例如下:class\interface.ts{//接口用于定义对象的形状,这个是TypeScript的功能(JavaScript中没有)interfacePerson{readonlyid:number;//只读......
  • 兼收并蓄 TypeScript - 基础: 基础
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:基础示例如下:basic\basic.ts{//基础//try/catch/finally的用法functionf1(str:string):number|null{try{letnum=Number(str......
  • 兼收并蓄 TypeScript - 基础: var, let, const
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:var,let,const示例如下:basic\var_let_const.ts//var声明的变量是全局作用域,块外也可用{vara=10;}console.log(a);//let声明的变量是块作用域,仅块内可用{......
  • 兼收并蓄 TypeScript - 基础: 数据类型
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:数据类型示例如下:basic\dataType.ts{//基本数据类型boolean,number,string,symbolleta:boolean=true;letb:number=10;letc:string="abc";......
  • 兼收并蓄 TypeScript - 基础: null, undefined
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:null,undefined示例如下:basic\null_undefined.ts{console.log(undefined==null,undefined===null);//truefalseconsole.log(typeofnull,typeofundefined);......
  • 兼收并蓄 TypeScript - 基础: boolean
    源码https://github.com/webabcd/TypeScriptDemo作者webabcd兼收并蓄TypeScript-基础:boolean示例如下:basic\boolean.ts{leta=true;console.log(a);//true//将指定类型的数据转换为boolean类型console.log(Boolean(100),Boolean(......
  • VUE 使用用Echart 报错:this.dom.getContext is not a function
    问题:在VUE中 如果使用了 tabs 关在tab 中加入了<div>标签;在初始化中 执行echart.init() 可能会报错:this.dom.getContextisnotafunction;大致如下所示:<el-tabs> <el-tab-pane><div>    <divstyle="height:500px;widows:1000px;"ref="homeLineRe......
  • 易优eyoucms网站报错 \core\library\think\App.php Fatal error: Call to undefin
    当你遇到 Fatalerror:Calltoundefinedfunctionthink\switch_citysite() 这样的错误时,说明在代码中调用了一个未定义的函数 think\switch_citysite()。这种情况通常是因为函数没有被正确地引入或者该函数根本不存在于当前的代码库中。解决方案确认函数的存在检查 s......
  • 解决React Warning: Function components cannot be given refs. Attempts to access
    问题当我使用如下方式调用组件子组件UploadModal并且绑定Ref时React报错“Warning:Functioncomponentscannotbegivenrefs.Attemptstoaccessthisrefwillfail.DidyoumeantouseReact.forwardRef()?”;constUploadModalRef=useRef(null);constopenUploadModa......
  • react react18+vite+typeScript+eslint+prettier+husky+lint-staged+commitlint 快速
    技术栈react18react-router6antd5zustand4vite45axiosfakerjs模拟数据dayjslodashtypescriptechartscommitlint、prettier、eslinthusky、lint-staged自定义commitlint、cz-cli自定义eslint、prettier代码规范技术栈代码格式规范和语法检测vscode:统一前端编辑器。editor......