#My type's property is a union. How do I convert it to a property of string?

9 messages · Page 1 of 1 (latest)

stark relicBOT
#
sleepeasysoftware#0

Preview:```ts
export type UrlMatcher = {
url: string | RegExp
}

export type SimpleUrlMatcher = unknown
/// I want this type: { url: string; }```

mossy pecan
#

!ts

stark relicBOT
#
export type UrlMatcher = {
  url: string | RegExp;
};

export type SimpleUrlMatcher = unknown;
/// I want this type: { url: string; }```
mossy pecan
#

I imagine there's a utility type or a set of utility types I can use instead of unknown to achieve the type I want, but I've been unable to figure out how to do it

stark relicBOT
#
sleepeasysoftware#0

Preview:```ts
export type UrlMatcher = {
url: string | RegExp
}

export type SimpleUrlMatcher = unknown
/// I want this type: { url: string; }

// This is what I tried:
type TestMatcher = Extract<UrlMatcher, {url: string}>
// ^?```

mossy pecan
#

Maybe this is the right way (TestMatcher2):

stark relicBOT
#
sleepeasysoftware#0

Preview:```ts
export type UrlMatcher = {
url: string | RegExp
}

export type SimpleUrlMatcher = unknown
/// I want this type: { url: string; }

// This is what I tried:
type TestMatcher = Extract<UrlMatcher, {url: string}>
// ^?

type TestMatcher2 = Record<keyof UrlMatcher, string>
...```

vague valley
#

if you want to change the value of every property in UrlMatcher to string

type TestMatcher = Record<keyof UrlMatcher, string>

If you want to change every property that is "string | RegExp" to "string", but leave the other ones untouched

type TestMatcher = {
  [K in keyof UrlMatcher]: string | RegExp extends UrlMatcher[K] ? string : UrlMatcher[K];
}
#

@mossy pecan I'm not sure what you want to do here, can you make the example a bit more complicated? with this simple version I can't see why not just { url: string; }