简体   繁体   English

覆盖 function 参数 - typescript

[英]Override function parameters - typescript

I have the following config.tsx file-我有以下config.tsx文件-

const AuthConfig = {
    base_uri: 'https://google.com',
    info: {
        country: 'Norway',
        continent: 'Europe',
    }
};
export default AuthConfig;

I am passing the content of this config file as a parameter in some other function call outside the config.tsx file.我将此配置文件的内容作为参数传递给config.tsx 文件之外的其他一些 function 调用。

import config from './config'

myFunction(config)

Question - Is it possible to override a value (say "continent") coming from config file at the time of function call?问题- 是否可以在 function 调用时覆盖来自配置文件的值(比如“大陆”)?

Yes you can do it with the spread operator or Object.assign是的,您可以使用扩展运算符或Object.assign

 myFunction({...config, info: {...config.info, continent: 'America'}})

Or或者

myFunction(Object.assign(config, {info: Object.assign(config.info, {continent: 'America'})})) 

Yes, you can simply cast the config to any type and then you can update the value for continent like:是的,您可以简单地将config转换为any类型,然后您可以更新continent的值,例如:

import config from './config'

(<any>config).continent = "AnotherOne";

// This is for debugging purpose
console.log( config )

myFunction(config);

If we don't cast the config to any, we will get an error like:如果我们不将config转换为任何配置,我们将收到如下错误:

Property 'continent' does not exist on type '{ base_uri: string;类型 '{ base_uri: string; 上不存在属性 'continent' info: { country: string;信息:{国家:字符串; continent: string;大陆:字符串; }; }; }'. }'。

If all you want is to change the values, but not the properties.如果您只想更改值,而不是属性。 spread the Object传播 Object

const AuthConfig = {
    base_uri: 'https://google.com',
    info: {
        country: 'Norway',
        continent: 'Europe',
    }
};
export default AuthConfig;

const toSend = {
   ...AuthService,
   info: { ...AuthService.info, continent: "Some Else" }
}

myFunc(toSend);

But if instead you want to alter the Object Structure.但是,如果您想更改 Object 结构。 TypeScript will cry. TypeScript 会哭。 So you need to create a ObjectLiteral type所以你需要创建一个ObjectLiteral类型

export interface ObjectLiteral {
  [x: string]: any;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM