const obj2={ [Symbol.iterator](){ let i=-1 const txt=[ 'this will output in both case', 'just output in call `next` by hand' ] return { next(){ i++ return {done:i===txt.length-1,value:txt[} } } } } const obj1={ [Symbol.iterator]:function* (){ yield'this will output in both case' return'just output in call `next` by hand' } } console.log('obj1 output') var g=obj1[Symbol.iterator]() console.log(g.next().value) console.log(g.next().value) console.log('----') for(let i of obj1){ console.log(i) } console.log('obj2 output') var g=obj2[Symbol.iterator]() console.log(g.next().value) console.log(g.next().value) console.log('----') for(let i of obj2){ console.log(i) } // => 输出结果:
// obj1 output // this will output in both case // just output in call `next` by hand // ---- // this will output in both case
// obj2 output // this will output in both case // just output in call `next` by hand // ---- // this will output in both case
However, TypeScript takes the stance that there’s probably a bug in this code. Object literals get special treatment and undergo excess property checking when assigning them to other variables, or passing them as arguments. If an object literal has any properties that the “target type” doesn’t have, you’ll get an error:
绕过excess property checking的方法
1 2 3
1. use a type assertion(类型断言) 2. add a string index signature(定义string型的索引签名) 3. One final way to get around these checks, which might be a bitsurprising, is to assign the object to another variable