ope*_*pex 4 typescript typescript2.0
In the current version (2.1) of TypeScript I can constrain a method argument on a generic class to be a property of the generic type.
class Foo<TEntity extends {[key:string]:any}> {
public bar<K extends keyof TEntity>(key:K, value:TEntity[K]) { }
}
Run Code Online (Sandbox Code Playgroud)
Is it possible in the current type system to constrain the key part even further to be a subset where the value of the key is of a certain type?
What I'm looking for is something along the lines of this psuedo code.
class Foo<TEntity extends {[key:string]:any}> {
public updateText<K extends keyof TEntity where TEntity[K] extends string>(key:K, value:any) {
this.model[key] = this.convertToText(value);
}
}
Run Code Online (Sandbox Code Playgroud)
EDIT
For clarification I added a more complete example of what I'm trying to achieve.
type object = { [key: string]: any };
class Form<T extends object> {
private values: Partial<T> = {} as T;
protected convert<K extends keyof T>(key: K, input: any, converter: (value: any) => T[K])
{
this.values[key] = converter(input);
}
protected convertText<K extends keyof T>(key: K, input: any)
{
this.values[key] = this.convert(key, input, this.stringConverter);
}
private stringConverter(value: any): string
{
return String(value);
}
}
Run Code Online (Sandbox Code Playgroud)
convertText will give an error saying that Type 'string' is not assignable to type 'T[K]'.
Given
interface Foo {
s: string
n: number
}
Run Code Online (Sandbox Code Playgroud)
The compiler can tell that this will work
this.convert('s', 123, v => String(v));
Run Code Online (Sandbox Code Playgroud)
and this will not
this.convert('n', 123, v => String(v));
Run Code Online (Sandbox Code Playgroud)
I'm hoping I can constrain the convertText method to keys where the value is of type string to get type safety on the key parameter.
这是可能的(此处使用非类示例)。下面将确保它T[P]是一个字符串。
function convertText<T extends {[key in P]: string }, P extends keyof T>(data: T, field: P & keyof T) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
这个想法是将 的类型缩小T到仅推断出的字段P并设置您想要的确切类型,在本例中为string。
测试:
let obj = { foo: 'lorem', bar: 2 };
convertText(obj, 'foo');
convertText(obj, 'bar'); // fails with: Type 'number' is not assignable to type 'string'.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2597 次 |
| 最近记录: |