There is a difference in how TypeScript infers the type automatically based on type of the argument we pass in:
- how the value is declared (inline or by reference)
- whether the value is an inline object with non-arrow function
The error is reproduced if generic parameter has default value undefined (this is mandatory in my case.)
🔎 Search Terms
- "generics in constructor"
- "type argument inference undefined"
🕗 Version & Regression Information
- This is the behavior in every version I tried from 3.9.7 to 5.9.3
⏯ Playground Link
💻 Code
This issue with function:
functionmake<T,S=T,D=undefined>(value: T,options: NewOptions<T,S,D>){return{v: value,data: options?.data,sourceValue: options?.sourceValue??value,finaleValue: options?.finaleValue,};}exporttypeNewOptions<T,S,D>={finaleValue?: T,sourceValue?: S,data: D,};constinstance_withError=make(0,{// Error here: `Type '{ test(): number; }' is not assignable to type 'undefined'.(2322)`?data: {test(){return123;},},});constdata={test(){return123;},};// no error hereconstinstance1=make(0,{// data is not inline object, BUT object with non-arrow function
data,sourceValue: 'test',finaleValue: 1,});// no error hereconstinstance2=make(0,{// data is inline object, BUT object with arrow functiondata: {test: ()=>{return123;},},sourceValue: 1,finaleValue: 2,});constsV1=instance2.sourceValue;// ^?constv1=instance2.v;// ^?constsV2=instance1.sourceValue;// ^?constv2=instance1.v;// ^?// Should be `{ test(): number; }`constdata_invalid=instance_withError.data;// ^?// Should be `{ test(): number; }`constdata1=instance1.data;// ^?// Should be `{ test: () => number; }`constdata2=instance2.data;// ^?🙁 Actual behavior
- An error occurs:
Type '{ test(): number; }' is not assignable to type 'undefined'.(2322) data type is undefined
🙂 Expected behavior
- No error occurs
data type is { test(): number; }
There is a difference in how TypeScript infers the type automatically based on type of the argument we pass in:
The error is reproduced if generic parameter has default value
undefined(this is mandatory in my case.)🔎 Search Terms
🕗 Version & Regression Information
⏯ Playground Link
💻 Code
This issue with function:
🙁 Actual behavior
Type '{ test(): number; }' is not assignable to type 'undefined'.(2322)
datatype isundefined🙂 Expected behavior
datatype is{ test(): number; }