#Exact iterator

12 messages · Page 1 of 1 (latest)

balmy lion
#

Is there any way can type iterator:

const iterator = ([1, 2, 3] as const)[Symbol.iterator]()

const first = iterator.next()
const second = iterator.next() 
const third = iterator.next() 

So that first is 1 instead of 1 | 2 | 3?

balmy lion
#

Basically functions or methods that “increment” the return type on each call.

zenith lagoon
#

I really doubt it.

#

Having a value change state as methods are called on is a very difficult pattern in TS in the best of cases.

#

I think there's some tricks you can do with method(): asserts this is SomeType but these tend to be limited and fragile

balmy lion
#

Do you have any examples?

gritty gardenBOT
#
declare class Foo {
  val: string | number;
  doThing(): asserts this is { val: string }
}

const x: Foo = new Foo()
x.doThing();
x.val
// ^? - (property) val: string
zenith lagoon
#

But again, this isn't great - this is pretty fragile (e.g. the type annotation on const x: Foo is not optional)

#

And the whole idea really falls apart when you have to deal with stuff like passing the iterator/class to a function where you don't know what will happpen to it.

balmy lion
#

Thanks, why is the annotation needed?

zenith lagoon
#

Not sure exactly; I just know that it's a limitation on assertions that the things they operate on need to have known types

balmy lion
#

Is there any way to make the assertion function also have a return value?