为什么即使提供有效的默认值后,我也无法解构可选参数?

时间:2018-08-10 09:42:10

标签: typescript

这仅仅是功能不足还是代码中的错误?

目标是使用户能够在不提供选项的情况下调用我的函数,并且仍然可以破坏签名中的选项。

'use strict';

exports.handler = (event, context, callback) => {
    console.log('Event: ', JSON.stringify(event, null, 2));
    console.log('Context: ', JSON.stringify(context, null, 2));
    const request = event.Records[0].cf.request;

    // You can also store and read the redirect map
    // in DynamoDB or S3, for example.
    const redirects = {
        '/r/music':    '/card/bcbd2481',
        '/r/tree':     '/card/da8398f4',
    };

    if (redirects[request.uri]) {
        return callback(null, {
            status: '302',
            statusDescription: 'Found',
            headers: {
                'location': [{ 
                    key: 'Location',
                    value: redirects[request.uri] }]
            }
        });
    }

    callback(null, request);
};

Interactive REPL here(请确保在REPL中启用// Typings export interface MyFunctionOptions { optParam?: boolean; } export type MyFunction = (mandatoryParam: string, opts?: MyFunctionOptions) => void; // Functions const myFunction: MyFunction = (mandatoryParam, { optParam, } = { optParam: false }) => { // use `optParam` directly, instead of `opts.optParam` return; }

1 个答案:

答案 0 :(得分:1)

为解构参数指定默认值的语法为{param = default}

function foo({param = true}) {
    console.log(param) // param is boolean
}

foo({}) // the parameter is required
foo({ param: true}) 

要使参数本身可选,我们可以为整个参数指定默认值{}

function foo({param = true} = {}) {
    console.log(param) // param is boolean
}

foo() // the parameter is optional

如果将这种逻辑应用于您的样本,我们将得到:

const myFunction = (mandatoryParam: string, { optParam = false } = {}) => {
    optParam
    return;
}
myFunction("") // not required
myFunction("", {}) // optParam is optional
myFunction("", { optParam: true }) // optParam can be set 

当我们尝试显式指定函数的类型时,就会出现问题,然后推断第二个参数为MyFunctionOptions | undefined,该参数无论如何都无法索引。对于这种不幸的推断的简单解决方案是显式指定解构参数的类型:

const myFunction: MyFunction = (mandatoryParam: string, { optParam = false } : MyFunctionOptions = {}) => {
    optParam
    return;
}
myFunction("")
myFunction("", {})
myFunction("", { optParam: true })

Playground link