I’m using the TS types (put together by Pablo) and with the help of VS code it is showing the errors but it is also showing errors when using base types.
[ts] Type ‘SceneNode’ is missing the following properties from type ‘GraphicsNode’: fill, fillEnabled, stroke, strokeEnabled, and 11 more. [2740]
So if my function accepts SceneNode but has code to handle sub classes like GraphicsNode and Rectangle and when I reference strokeEnabled it shows an error. That’s expected since SceneNode doesn’t have that property.
Initial code accepts SceneNode:
/**
* Adds a transform to a SceneNode
* @param {SceneNode} item
* @param {Object} transform
*/
function transformSceneNode(item, transform) {
if (item.strokeEnabled) { // warning here
}
}
So I added in the base class that has that property:
Accepts SceneNodes and GraphicsNodes code:
/**
* Adds a transform to a SceneNode
* @param {SceneNode|GraphicsNode} item
* @param {Object} transform
*/
function transformSceneNode(item, transform) {
if (item.strokeEnabled) { // warning still here
}
}
Error:
Property ‘strokeEnabled’ does not exist on type ‘GraphicsNode | SceneNode’.
Property ‘strokeEnabled’ does not exist on type ‘SceneNode’. [2339]
I checked the types and it says GraphicsNode strokeEnabled proeprty.
So I finally attempted to cast to type and use the type.
Accepts SceneNodes and GraphicsNodes and assigns to desired type:
/**
* Adds a transform to a SceneNode
* @param {SceneNode|GraphicsNode} item
* @param {Object} transform
*/
function transformSceneNode(item, transform) {
/** @type {GraphicsNode} */
var graphicsNode = item; // warning here
if (graphicsNode.strokeEnabled) {
}
}
And I get this warning:
Type ‘GraphicsNode | SceneNode’ is not assignable to type ‘GraphicsNode’.
So then I use the as
operator like this:
Casts SceneNodes and GraphicsNodes using as
to GraphicsNode type:
/**
* Adds a transform to a SceneNode
* @param {SceneNode|GraphicsNode} item
* @param {Object} transform
*/
function transformSceneNode(item, transform) {
/** @type {GraphicsNode} */
var graphicsNode = item as GraphicsNode; // warning here
if (graphicsNode && graphicsNode.strokeEnabled) {
}
}
But that gives this error:
[ts] ‘type assertion expressions’ can only be used in a .ts file. [8016]
[ts] Cannot find name ‘GraphicsNode’. [2304]
So finally I am doing this:
Accepts SceneNodes and GraphicsNodes and sets variable only if instance of GraphicsNode:
/**
* Adds a transform to a SceneNode
* @param {SceneNode} item
* @param {Object} transform
*/
function transformSceneNode(item, transform) {
/** @type {GraphicsNode} */
var graphicsNode = item instanceof GraphicsNode ? item : null;
if (graphicsNode && graphicsNode.strokeEnabled) {
}
}
I’m new to ES6 and have not used TypeScript. Is there a better way to handle the use cases above?