在typescript类型中对对象键名施加一些模式

在typescript类型中对对象键名施加一些模式,typescript,Typescript,在typescript中,是否可以声明一个类型,声明其属性具有某些给定的模式,例如,它们都以字符w结尾 对于本例,以下是一个符合该类型的对象: { "250w": ..., "1024w": ..., "300w": ... } 以下对象不符合(与上面给出的示例一致): 我在想这样的事情: interface MyCrazyType { [key ????]: any; } 使用typescript 4

在typescript中,是否可以声明一个类型,声明其属性具有某些给定的模式,例如,它们都以字符
w
结尾

对于本例,以下是一个符合该类型的对象:

{
    "250w": ...,
    "1024w": ...,
    "300w": ...
}
以下对象不符合(与上面给出的示例一致):

我在想这样的事情:

interface MyCrazyType {
   [key ????]: any;
}

使用typescript 4.1和模板文字类型,您可以在有限的程度上使用它们。你可以这样做

type alphaNumeric = 'a'|'b'|'c'|'d' //you can take this to the extreme of all letters and numbers
type specialPattern = `${alphaNumeric}${alphaNumeric}w` | `${alphaNumeric}w` //this is limited to less than 1000 combinations see https://github.com/microsoft/TypeScript/pull/40336

let a:specialPattern = 'ab' //typescript complains because it does not end with w
a = 'abw' //good
a = 'aw' //good
a = 'abcw' //bad - more than two characters in front of the w

对于您的具体情况,类型为

type mMyCrazyType = Record<specialPattern,any>
类型mMyCrazyType=记录

Typescript每天都有越来越多的功能,哈哈。我希望他们能够保持所有这些功能。为了完整地回答这个问题,告诉OP如何真正获得他想要的类型可能会很有用。类似于
typemyCrazyType=Record为此找到了一个
type mMyCrazyType = Record<specialPattern,any>