如何在Typescript上为字符串键入点表示法



我正在尝试构建一个函数API,如下所示:

createRoute('customers.view', { customerId: 1 });  // returns `/customers/1`

然而,我在输入第一个论点时遇到了麻烦。到目前为止,我拥有的是:

const uris = {
customers: {
view: '/customers/:customerId',
},
users: {
list: '/users',
}
};
const createRoute = (route: string, routeParams: { [key: string]: string }) => {
/**
* This will split 'customer.view' each on a variable
*/
const [ resource, action ] = route.split('.');
/**
* HERE:  I'm getting this error:
*  
*   Element implicitly has an 'any' type because expression of type 'string' 
*   can't be used to index type '{ customers: { view: string; } }'.
*
*/
const uri = uris[resource]?.[action]

// ... rest of code to replace the route param...
};

我理解这个错误的含义。函数签名允许我传递任何string,但应限制为uri对象的有效密钥。

此外,字符串的第二部分取决于第一部分(毕竟是嵌套对象(。

可以打这个吗?

您还可以执行以下操作,这样您就可以获得::

createRoute(['customers', 'view'], {}); // compile
createRoute(['users', 'list'], {}); // compile
createRoute(['users', 'view'], {}); // DOESN'T compile: Type '["users", "view"]' is not assignable to type 'Route<ICustomerUri>'.
createRoute(['nota router'], {}); // DOESN'T compile: Type '"nota router"' is not assignable to type '"customers" | "users"'

代码:

interface ICustomerUri {
customers: {
view: string;
};
}
interface IUsersUri {
users: {
list: string;
};
}
type Route<T> = [keyof T, keyof T[keyof T]];
type Routers = Route<ICustomerUri> | Route<IUsersUri>;
interface IUris extends ICustomerUri, IUsersUri {}
const uris: IUris = {
customers: {
view: '/customers/:customerId',
},
users: {
list: '/users',
}
};
const createRoute = (route: Routers, routeParams: { [key: string]: string }) => {
// your implementation
}

游乐场链接

这种格式应该适用于您:

const resource = route.split('.')[0] as keyof typeof uris;
const action = route.split('.')[1] as keyof typeof uris[typeof resource];

游乐场链接

感谢大家的投入。这些方法要么过于复杂,要么实际上没有提供类型安全性。相反,我选择了一个更简单的:

const uris= {
'customers.view': '/customers/:customerId',
'users.list', '/users',
};
type Route = keyof typeof routePatterns;
const createRoute = (route: Route,  ...

最新更新