Skip to content

make Strings.startsWith to support ${Prefix}${string} #54971

Closed
@zhujinxuan

Description

@zhujinxuan

lib Update Request

Sometimes, we might make a more specific definition on string type to avoid confusion in programming. For example:

const statePrefix = `State/` as const
type State = `${typeof statePrefix}${string}`
const customerIdPrefix = `Customer/` as const
type CustomerId = `${typeof customerIdPrefix}`

In this way, we can distinguish state and customerId, rather than using string everywhere. For example, we can clearly know a structure of a dictionary like

// Avoid confusion of Map<string, Map<string, boolean>>
const IsActiveCustomerMap = new Map<State<Map<CustomerId, boolean>>>()

So, I suggest adding startsWith definition to understand literal types. I would suggest this definition added to the library in addition to the original definition:

    startsWith<T extends string>(searchString: T, position?: 0): this is `${T}${string};

This definition can help us simplify the specific string definition.

Configuration Check

My compilation target is ES2015 and my lib is the default.

Missing / Incorrect Definition

Add to Strings:

    startsWith<T extends string>(searchString: T, position?: 0): this is `${T}${string};

Sample Code

function mkPrefix<T extends string>(prefix: T, key: string): `${T}${string}` {
  if (key.startsWith(prefix)) return key;
  return `${prefix}${key}`
}

Documentation Link

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions