我正在尝试创建一个泛型类型,其中从该类型的属性之一推断出泛型参数类型。简化的情况:
==> ubuntu: Running action triggers before up ...
==> ubuntu: Running trigger: Hello world...
==> ubuntu: I am running before vagrant up!!
....
==> ubuntu: Running action triggers after up ...
==> ubuntu: Running trigger: Hello world...
==> ubuntu: I am running after vagrant up!!
我正在将其与类似的函数模式进行比较,可以从用法中推断出泛型类型参数:
// with this setup
const permissionGroups = {
users: ['read'],
scripts: ['execute'],
} as const;
type PermissionGroups = typeof permissionGroups;
// this would be nice, but does not work
type PermissionToCheck = <T extends keyof PermissionGroups>{
group: T;
permission: PermissionGroups[T][number];
};
function checkPermission(permissionToCheck: PermissionToCheck) {}
// this does, but is inconvenient
type PermissionToCheck<T extends keyof PermissionGroups> = {
group: T;
permission: PermissionGroups[T][number];
};
function checkPermission<T extends keyof PermissionGroups>( // repeated generic constraint
permissionToCheck: PermissionToCheck<T>,
) {}
有什么方法可以避免每次我使用type SomeCallback = <T>(arg: T[]) => T;
function doStuff(callback: SomeCallback) {
const result = callback([1,2]); // result is number, no need for explicit type anywhere
}
类型并且仍然进行正确的类型检查时都传递通用参数吗?