TS type different String / string



TS type different String / string

 

TS type different String / string_String / string

TS type different String / string_TS type different_02

Object vs object

TS type different String / string_TS type different_03


class SVGStorageUtils {
// Object
store: Object;
// object
constructor(store: object) {
this.store = store;
}
// string primitive
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
// String Object
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
clear(key: any) {
delete this.store[key];
}
clearAll() {
this.store = {};
}
init() {
this.store = {};
}
}






TypeScript: ​​String​​ vs ​​string​

Argument of type 'String' is not assignable to parameter of type 'string'.

'string' is a primitive, but 'String' is a wrapper object.

Prefer using 'string' when possible.

demo

String Object

// error
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: String = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: String = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}


string primitive

// ok
class SVGStorageUtils {
store: object;
constructor(store: object) {
this.store = store;
}
setData(key: string = ``, data: object) {
sessionStorage.setItem(key, JSON.stringify(data));
}
getData(key: string = ``) {
const obj = JSON.parse(sessionStorage.getItem(key));
}
}