#How to separate string in an intersection type?

8 messages · Page 1 of 1 (latest)

clear wave
#

I tried to find a way to extract the string type from an intersection type. Is there a way to do that?

i.e.:

type R = Extract<string & { a: 1 }> // string

type R1 = Extract<`abc` & { a: 1 }> // `abc`
type R2 = Extract<`${number}` & { a: 1 }> // `${number}`
type R3 = Extract<`a ${Uppercase<string>}` & { a: 1 }> // `a ${Uppercase<string>}`
paper inletBOT
#
mishall8399#0

Preview:```ts
type OtherKeys<T> = Exclude<keyof T, keyof string>
type OtherPart<T> = Pick<T, OtherKeys<T>>
type ExtractStr<T> = [T] extends [OtherPart<T> & (infer X)] ? X : never

type R = ExtractStr<string & { a: 1 }> // string

type R1 = ExtractStr<abc & { a: 1 }> // abc
...```

round dawn
#

It fails in cases such as this tho
ExtractStr<'abc' & { toString: 1 }>

clear wave
#

Cool. That looks great. It is a great starting point. I can add more tests for it and expand from there.

Thank you!

brave hemlock
clear wave
#

@brave hemlock That's very interesting. It seems to work in all cases.

brave hemlock
#

!resolved