So, I want to create TS class with optional param and fallback it's keys:
class NiceClass {
private format: string;
private total: number;
private current: number;
private width: number;
private head: string;
private complete: string;
private incomplete: string;
private tail: string;
constructor (format: string, total: number, options?: any) {
this.format = format;
this.total = total;
if (options) {
this.current = (typeof options.current == 'number') ? options.current : 0
this.width = (typeof options.width == 'number') ? options.width : 20
this.head = (typeof options.head == 'string') ? options.head : '^'
this.complete = (typeof options.complete == 'string') ? options.complete : '+'
this.incomplete = (typeof options.incomplete == 'string') ? options.incomplete : '-'
this.tail = (typeof options.tail == 'string') ? options.tail : '$'
} else {
this.current = 0
this.width = 20
this.head = '^'
this.complete = '+'
this.incomplete = '-'
this.tail = '$'
}
}
public async add(increase: number = 1): Promise<void> {
// some functionallity
}
}
export default NiceClass;
So it can be used like so:
const nice = new NiceClass('nice format', 50); // without any option
// or
const nice = new NiceClass('nice format', 50, { // with some option(s)
current: 25,
head: '/'
});
// or
const nice = new NiceClass('nice format', 50, { // with all options
current: 25,
width: 5,
head: '/',
complete: 'x',
incomplete: ' ',
tail: '\'
});
The above script works fine, but I think it could be improved and look much cleaner, since:
- TS allows defining fallback values like so:
(increase: number = 1)instead ofthis.increase = (typeof increase == 'number') ? increase : 0 - TS allows creating optional arguments like so
(options?: any)
The problem is I can't figure it out how to do this
P.S: I'm totally new to TS, so sorry if it's basic stuff.