typescript参数属性-TypeScript 中对象参数的默认值

默认参数是用户希望一直合并到代码中的东西。 TypeScript 能够在对象中提供默认参数并在函数中传递对象。

本教程将重点介绍如何在 TypeScript 中使用默认参数。

TypeScript 中对象的默认值

如果没有值传递给函数,则可以将函数定义为使用默认值。 以下代码片段演示了如何执行此操作。

<code class="language-typescript" data-lang="typescript">interface Config {
    file :  string ;
    test : boolean;
    production : boolean;
    dbUrl : string;
}
function getConfig ( config : Config = { file : 'test.log', test : true,
    production : false, dbUrl : 'localhost:5432' }) {
        console.log(config);
}


getConfig();

getConfig({file : 'prod.log', test: false, production : true, dbUrl : 'example.com/db'});

参数属性revit_typescript参数属性_参数属性怎么打开

输出:

{
  "file": "test.log",
  "test": true,
  "production": false,
  "dbUrl": "localhost:5432"
}

{
  "file": "prod.log",
  "test": false,
  "production": true,
  "dbUrl": "example.com/db"
}

上面展示了如何在 TypeScript 中使用默认值。

如果调用函数时没有传递Config对象的值,getConfig函数将使用函数定义中分配的默认值,这一点可以从第一次调用getConfig函数的情况看出。

typescript参数属性_参数属性怎么打开_参数属性revit

第二次调用该函数时,默认值将被传递给该函数的值覆盖。

在 TypeScript 中通过重构传递默认值

TypeScript 还支持通过重构对象属性向函数传递默认值。 以下代码片段显示了这是如何完成的。

interface Person {
    firstName : string ;
    lastName : string ;
}

function getPerson( {firstName  = 'Steve',  lastName = 'Jobs' } : Person ) {
    console.log( firstName + ' ' + lastName);
}

getPerson({} as Person);

getPerson({ firstName : 'Tim', lastName : 'Cook'});

输出:

"Steve Jobs"
"Tim Cook"

因此,如上例所示,对函数 getPerson 进行了两次调用,一次使用默认值,另一次使用传递给函数的值。 不同之处在于,默认情况下,会传递一个空对象 {},否则 TypeScript 将抛出错误 - Expected 1 arguments, but got 0。

在 TypeScript 中使对象的各个属性具有默认值

当为对象分配属性或将对象传递给函数时,我们可以使对象的各个属性具有默认值,而其他属性则需要。 这可以通过使用 ? 来完成。 操作员。

以下代码片段显示了它是如何完成的。

interface Config {
    file? :  string ;
    test? : boolean;
    production : boolean;
    dbUrl : string;
}


function getConfig( { file = 'api.log', test = true, production, dbUrl} : Config ) {
    var config : Config = {
        file,
        test,
        production,
        dbUrl
    };
    console.log(config);
}

getConfig({production : true, dbUrl : 'example.com/db'});

输出:

{
  "file": "api.log",
  "test": true,
  "production": true,
  "dbUrl": "example.com/db"
}

在 TypeScript 中使用 Partial 关键字使所有数组都有默认值

Partial 关键字是一个有用的工具,可以使对象的所有属性都可选,并且可以用于在函数定义的情况下使对象的所有数组都具有默认值。 使用前面的例子。

interface Config {
    file :  string ;
    test : boolean;
    production : boolean;
    dbUrl : string;
}


function getConfig( { file = 'api.log', test = true, production = false, dbUrl = 'localhost:5432'} : Partial<Config> ) {
    var config : Config = {
        file,
        test,
        production,
        dbUrl
    };
    console.log(config);
}

getConfig({production : true});

输出:

{
  "file": "api.log",
  "test": true,
  "production": true,
  "dbUrl": "localhost:5432"
}

因此typescript参数属性typescript参数属性,在前面的示例中,我们可以看到所有数组都有默认值,并且 Production 属性的值已被覆盖。