I have a generic function which takes in an object, however the object cannot contain properties with the format __property__
. Currently I do:
我有一个接受对象的泛型函数,但是该对象不能包含格式为__PROPERTY__的属性。目前我做的是:
type RemoveProps = {
[K in keyof T as K extends `__${infer _K}__` ? never : K]: T[K];
}
function doSomething<T extends {}>(arg: RemoveProps<T>):
{
// ...
}
This is fine, but it still allows you to do:
这很好,但它仍然允许您执行以下操作:
doSomething<{ __not_allowed__: any }>(arg);
Is there a way to get typescript to throw an error if the generic type contains these properties?
如果泛型类型包含这些属性,有没有办法让TypeScrip抛出一个错误?
更多回答
This might be a problem better solved with an ESLint rule that allows you to ban certain named properties based on a regex pattern. A quick search and I found this project which might do it, but I haven't looked into it very thoroughly
这可能是使用ESLint规则更好地解决这个问题,该规则允许您禁止基于正则表达式模式的某些命名属性。我快速地搜索了一下,发现了这个可能做到这一点的项目,但我还没有非常彻底地研究过它
@ChrisBarr That would be fine if the rule wasn't applied project wide, but its only to the function. Besides the reason for excluding them is because the internals utilize variables of that format that the user shouldn't use.
@ChrisBarr如果这条规则不适用于整个项目,那就好了,但它只适用于函数。此外,排除它们的原因是内部使用了用户不应该使用的该格式的变量。
@jcalz Ah yeah that approach works perfectly haha, I forgot you can just map it to never instead of doing a conditional map on the key, thanks! Feel free to write up a full answer.
@jcalz啊是的,这种方法非常有效哈哈,我忘了你可以把它映射到Never,而不是在键上做条件映射,谢谢!你可以写一份完整的答案。
优秀答案推荐
I think the easiest way to do this is to map bad property value types to the impossible never
type instead of omitting them entirely. Omitting a property doesn't prevent assignability: { __x__: 0, y: 1 }
extends { y: 1}
but it does not extend { __x__: never, y: 1 }
:
我认为最简单的方法是将错误的属性值类型映射到不可能的永不类型,而不是完全忽略它们。省略属性不会阻止可赋值:{__x__:0,y:1}扩展{y:1},但不扩展{__x__:永不,y:1}:
type ProhibitProps<T> = {
[K in keyof T]: K extends `__${string}__` ? never : T[K]
}
function doSomething<T extends ProhibitProps<T>>(
arg: T
) { }
doSomething<{ __not_allowed__: any }>({ ok: 123 }); // error!
// -------> ~~~~~~~~~~~~~~~~~~~~~~~~
// Type '{ __not_allowed__: any; }' does not satisfy the
// constraint 'ProhibitProps<{ __not_allowed__: any; }>'.
// Types of property '__not_allowed__' are incompatible.
// Type 'any' is not assignable to type 'never'.
doSomething<{ ok: 123 }>({ ok: 123 }); // okay
Looks good!
看上去不错!
Playground link to code
游乐场链接到代码
更多回答
我是一名优秀的程序员,十分优秀!