简体   繁体   中英

Passing optional parameter in typescript when setting cache

I am setting some values in cache using cache-manager & mongoose-cache-manager npm module.

public setCache(key:string, value:string, options?:SomeType) {
   this.set(key,value,options); 
}

interface SomeType {
   ttl?:number 
}

So I have two scenarios where I need to pass options & I donot need to pass options.

Scenario 1: setCache('key', value, {ttl: 3600});
Scenario 2: setCache('key2', value2);

I am using both scenarios. But where I am getting stuck is like, If user doesn't pass options params (Scenario2) what will be the effect? Inorder to make both scenarios work together what can I do? Do I need to pass default as undefined in setCache function defenition?

Any suggestion would be really appreciated.

Thanks

Set a default value for options parameter, so if user don't pass it use the default value

public setCache(key:string, value:string, options:SomeType={ttl:3600}) {
   this.set(key,value,options); 
}

You can set the default values in typescript. eg: options:SomeType={ttl:2000}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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