-
Notifications
You must be signed in to change notification settings - Fork 12.8k
Question: keys of a type which have a certain type #18211
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is not a support forum. Questions should be asked at StackOverflow or on Gitter.im. Also, it seems to work as you would expect, unless I am missing something: class View<T> {
public sortBy(source: T[], property: keyof T): void {
}
}
const v = new View<{ id: number; name: string; }>();
v.sortBy([], 'name'); |
Thank you for your reply. It's my bad, I used the type It should work with As far as I know, it is not possible now, but a workaround might exists like in #18133 or it might be a proposal for future versions. It is also very similar to #13214. |
There is a workaround but keep in mind that these workarounds are quite fragile. E.g. try to make type HasKey<T, Key extends string> = (
{ [K in keyof T]: 'true' } &
{ [key: string]: 'false' }
)[Key]
// if the type has a `charCodeAt` property we deem it a `string`
// obviously, this might not always be the case
type IsString<T> = HasKey<T, 'charCodeAt'>
type StringProps<T> = {
[K in keyof T]: {
'true': K,
'false': never
}[IsString<T[K]>]
}[keyof T]
class View<T> {
public sortBy<K extends StringProps<T>>(_source: T[], _property: K): void {
}
}
const v = new View<{
id: number;
name: string;
description: string;
}>();
v.sortBy([], 'description'); |
TS 2.8 export type StringProps<T> = ({ [P in keyof T]: T[P] extends string ? P : never })[keyof T]; nb: this one will also allow |
Nice @VinceOPS Any way to make it work on private methods? class SomeClass {
public prop;
constructor() {}
public someMethod() {}
private somePrivateMethod() {}
private other() {
this.callWithThis('prop'); // proper warning, since it's not a Function
this.callWithThis('someMethod'); // properly no warning, since it's a Function
this.callWithThis('somePrivateMethod'); // warning since it's private
}
private callWithThis(classFnName: MethodProp) {
const self = this;
return () => { return self[classFnName].call(self); };
}
}
type MethodProp = ({
[T in keyof SomeClass]: SomeClass[T] extends Function ? T : never
})[keyof SomeClass] |
The type system is awesome, but I am struggling with this problem.
Is it possible to restrict the second parameter to those keys of
TModel
which type isstring
?For example, if I have an object like this:
Then the only allowed key is
"name"
.If not supported now,
Thanks.
The text was updated successfully, but these errors were encountered: