What is the difference between {} and Object?

Recently, I am confused by the difference between {}and Object. Sometimes it {}will solve my problem, sometimes it is impossible, and I switched from Object. I really don't know why.

I did some tests, hope this can give you some hint.

const t: Array<{label: string}> = [{label:'1'}];
const arr: Array<{}> = t; //error
const arr2: Array<Object> = t; //pass
+6
source share
4 answers

{}is an alias for new Object().

So, you can say that Object- this class, but {}- of instancethis class.

You can look here:

console.log(JSON.stringify(new Object()) == JSON.stringify({}))

console.log({} instanceof Object)
Run codeHide result
+2
source

, Github: [ ] .

class A {}
class B extends A {}
var bs: Array<B> = [];
var as: Array<A> = bs;
as.push(new A); // this would be bad!

, Array<B> Array<A>, A A, .

Object ,

Object - supertype subtype . , Object / , any.

@Tushar Acharekar @Ayush Gupta, .

+2

Flow, : https://flow.org/try/, : Type argument 'T' is incompatible. Property 'label' is incompatible Property not found.

, t Sealed Objects, arr - .

, t arr2, arr2 - ( Javascript). arr2. arr2 .

, :

const t: Array<{label: string}> = [{label:'1'}];
const t1: {label: string} = {label: `1`};
const w: Array<{label: string}> = [t1];
const t2: {label: string} = {label: `2`};
w.push(t2);

:

let w: Array<{label: string}> = [];
const t3: {} = {};
w.push(t3);

:

const u: Array<Object> = [{label:'1'}];
const arr: Array<{}> = u;   

const v: Array<{}> = [{label:'1'}];
const arr2: Array<Object> = v;  

const t3: {foo: number} = {foo:1};
arr2.push(t3);
0

, - ( ) . , .

  • {} key:value paire.
  • new Object() , Method1, Method2

.

var d = new Object();           //This is the simplest way to create an empty object.
var a = Object.create(null);    //This method creates a new object extending the prototype object passed as a parameter.
var b = {};                     //This is equivalent to Object.create(null) method, using a null prototype as an argument.

1:

var Animal = {
  type: 'Invertebrates',  // Default value of properties
  displayType: function() {  // Method which will display type of Animal
    console.log(this.type);
  }
};
var animalObject = Object.create(Animal);
animalObject.displayType();         // Output:Invertebrates
var fish = Object.create(Animal);
fish.type = 'Fishes';
fish.displayType();                 // Output:Fishes

2:

var Obj = function(name) {
  this.name = name
}
var c = new Obj("hello"); 

Dicoverign Javascript - The Best Video to Find Outjavascript prototype

0
source

All Articles