I'm playing with some code, which resolve generic type of property value and doesn't allow provide wrong value. But when I change from TValue
to (t: TValue) => TValue
, type TValue
doesn't going resolved more. It's now unknown {}
type, not number
more
Example without function. Working good
type ProtoOf<T> = Pick<T, keyof T>;
function decorate<TValue>(value: TValue) {
return <T extends { [KA in TKey]: TValue }, TKey extends keyof T>(
proto: ProtoOf<T> & { [P in TKey]: TValue },
propertyKey: TKey
) => {};
}
class Foo {
// TS error: none
// Result: EXPECTED
@decorate(1) bar: number = 1;
// TS Error:
// Types of property 'wrongBar' are incompatible
// Type 'number' is not assignable to type 'string'
// Result: EXPECTED
@decorate('') wrongBar: number = 1;
}
Example with function. Don't working as expected
type ProtoOf<T> = Pick<T, keyof T>;
function decorate<TValue>(getValue: (t: TValue) => TValue) {
return <T extends { [KA in TKey]: TValue }, TKey extends keyof T>(
proto: ProtoOf<T> & { [P in TKey]: TValue },
propertyKey: TKey
) => {};
}
class Foo {
// TS Error: Operator '+' cannot be applied to types '{}' and '1'
// Result: NOT EXPECTED: because we can assign `number` to `number`
@decorate(v => v + 1) bar: number = 1;
// TS error: none
// Result: NOT EXPECTED: we should have error, we cannot assign `string` to `number`
@decorate(v => v + '') wrongBar: number = 1;
}
I'm expected TValue
equal number
in example with function as in example without function