- Notifications
You must be signed in to change notification settings - Fork 13.2k
Description
interfaceA{prop: {x: number;y: number;}}Trying to associate the type of prop with a variable would lead to an error:
letp: A.prop;// Error: cannot find namespace AAside from anonymous object interfaces, it could also be allowed for function types:
interfaceA{func(arg: number): string}letf: A.func;// type of f is now func(arg: number): stringf=(arg: number)=>"hello";// OKPrimitive types:
interfaceA{prop: boolean;}letval: A.prop;// type of val is now booleanval=true;// OKAnd also when the types are nested:
interfaceA{outerProp: {innerProp: {x: number;y: number;}}}letp: A.outerProp.innerProp;// type of p would now be{x: number, y:number}p={x: 42,y: 24}//OKThe current workaround (the best that could I find, at least [edit: I added an additional one that uses typeof in the next comment]) is to define the type of prop as a named interface or alternatively use the type keyword.
interfacePropInterface{x: number;y: number;}// Or, alternatively:typePropInterface={x: number,y: number};interfaceA{prop: PropInterface;}letp: PropInterface;// OKBut that isn't always necessary or elegant, especially if the types are nested or generic (short example below).
This can also be extended to types defined through the type keyword or when using typeof SomeClass. Or even with generics:
interfaceA<T>{prop: {func: (val: T)=>T}}letf: A<number>.prop.func// working around this may be possible, but wouldn't be pretty.A real-world use case I encountered was casting a value into the type of an interface member from a union that includes it (this happened when thinking about issues with assignability of merged/intersected types):
letmerged: AmergeB;// Also happens with intersection: A & Bletobj: A;obj.prop=<A.prop>merged.prop;// the type of merged.prop is the union A.prop | B.prop// Edit: It turns out that a relatively simple workaround is possible with the 'typeof' operator, // that is explained in the next comment:obj.pro=<typeofobj.prop>merged.prop;@RyanCavanaugh Too Complex? Perhaps at least keep it as an option for the future?