如何在 TypeScript 中将特定字符串类型转换为小写?

问题描述 投票:0回答:1

我必须将定义为

'GET' | 'POST' | 'PATCH' | 'DELETE'
的特定字符串更改为小写,而不丢失有关类型的信息。当我只执行
method.toLowerCase()
时,它会将其类型更改回
string
。我必须实现像
'get' | 'post' | 'patch' | 'delete'
这样的目标。我可以使用泛型和类型断言来做到这一点,如下所示:

type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';

export function request(method: Method) {
    innerRequest(toLowerCase(method))
}

function innerRequest(method: Lowercase<Method>) {
    console.log(method)
}

function toLowerCase<S extends string>(text: S) {
    return text.toLocaleLowerCase() as Lowercase<S>;
}

我想知道是否有更好的方法来实现这一点,而不使用类型断言(

as Lowercase<S>
)?或者像这样使用它是一个好方法吗?

typescript
1个回答
0
投票

这不是开箱即用的。但是您可以通过将

toLocaleLowerCase()
的类型扩展为
generic
来实现此目的:

type Method = 'GET' | 'POST' | 'PATCH' | 'DELETE';

declare global {
interface String {
    toLocaleLowerCase<T extends string>(this: T): Lowercase<T>;
}
}

export function request(method: Method) {
    innerRequest(toLowerCase(method))
}

function innerRequest(method: Lowercase<Method>) {
    console.log(method)
}

function toLowerCase<S extends string>(text: S) : Lowercase<S> {
    return text.toLocaleLowerCase();
}

游乐场

© www.soinside.com 2019 - 2024. All rights reserved.