In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the Typescript type checking principle of Override how to achieve the relevant knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this Typescript type checking principle of Override how to achieve the article will have a harvest, let's take a look.
What are override modifiers for?
First, let's take a look at what this modifier does: the method marked by override must exist in the parent class, or an error will be reported.
Class Animal {getName () {return'';}} class Dog extends Animal {override bak () {return 'wang';} override getName () {return' wang';}}
The above code will report an error: This member cannot have an 'override' modifier because it is not declared in the base class' Animal'. That is to say, the overridden method does not exist in the parent class, which can avoid removing some methods that need to be rewritten in the subclass when the parent class is reconstructed.
How to implement type checking of override modifiers
In fact, all modifiers, including override, public, static, etc., exist as a property after parse becomes AST, and so is this override. Let's take a look at it through astexplorer.net.
You can see that the override property is true. In this way, we can filter out all the ClassMethod of the class that require override through this attribute.
You can then get the name of the superClass, find the corresponding declaration in the scope, and then traverse the AST to find all the ClassMethod it declares.
By comparison, all ClassMethod that are not in the parent class need to report an error.
Code implementation
We do parser and analysis based on babel, and write a plug-in to do type checking of override.
Open the syntax typescript plug-in to parse ts syntax.
Const {transformFromAstSync} = require ('@ babel/core'); const parser = require ('@ babel/parser'); const ast = parser.parse (sourceCode, {sourceType: 'unambiguous', plugins: [' typescript']}); const {code} = transformFromAstSync (ast, sourceCode, {plugins: [overrideCheckerPlugin]})
The plug-in is dealing with ClassDeclaration. Let's build a basic structure first:
Const {declare} = require ('@ babel/helper-plugin-utils'); const overrideCheckerPlugin = declare ((api, options, dirname) = > {api.assertVersion (7); return {pre (file) {file.set ('errors', []); visitor: {ClassDeclaration (path, state) {const semanticErrors = state.file.get (' errors') / /... State.file.set ('errors', semanticErrors);}, post (file) {console.log (file.get (' errors'));})
The specific check logic is to get all the method names of the parent class, get all the override method names of the current class, and then filter.
We first need to get the ast of the parent class and look it up from the scope by name.
Const superClass = path.node.superClass; if (superClass) {const superClassPath = path.scope.getBinding (superClass.name) .path;}
Then encapsulate a method to take the parent method name, traverse the ast through path.traverse, and store the collected method name in state.
Function getAllClassMethodNames (classDeclarationNodePath) {const state = {allSuperMethodNames: []} classDeclarationNodePath.traverse ({ClassMethod (path) {state.allSuperMethodNames.push (path.get ('key'). ToString ()}); return state.allSuperMethodNames;}
This gives you all the parent class method names.
After that, you need to get all the method names of the current class and filter out the error reports that the override is true and is not in the parent class.
Const superClass = path.node.superClass; if (superClass) {const superClassPath = path.scope.getBinding (superClass.name) .path; const allMethodNames = getAllClassMethodNames (superClassPath); path.traverse ({ClassMethod (path) {if (path.node.override) {const methodName = path.get ('key'). ToString (); const superClassName = superClassPath.get (' id'). ToString () If (! allMethodNames.includes (methodName)) {/ / error});}
The part of the error report uses code frame to create a friendly code print format, and the call stack information is removed by setting the Error.stackTraceLimit to 0.
Const tmp = Error.stackTraceLimit; Error.stackTraceLimit = 0; let errorMessage = `this member cannot have an 'override' modifier because it is not declared in the base class' ${superClassName}'`; semanticErrors.push (path.get ('key') .buildCodeFrameError (errorMessage, Error)); Error.stackTraceLimit = tmp
In this way, we have completed the type checking of override, and the overall code is as follows:
Const {declare} = require ('@ babel/helper-plugin-utils'); function getAllClassMethodNames (classDeclarationNodePath) {const state = {allSuperMethodNames: []} classDeclarationNodePath.traverse ({ClassMethod (path) {state.allSuperMethodNames.push (path.get ('key'). ToString ())}); return state.allSuperMethodNames } const overrideCheckerPlugin = declare ((api, options, dirname) = > {api.assertVersion (7); return {pre (file) {file.set ('errors', []);}, visitor: {ClassDeclaration (path, state) {const semanticErrors = state.file.get (' errors'); const superClass = path.node.superClass If (superClass) {const superClassPath = path.scope.getBinding (superClass.name) .path; const allMethodNames = getAllClassMethodNames (superClassPath) Path.traverse ({ClassMethod (path) {if (path.node.override) {const methodName = path.get ('key') .toString (); const superClassName = superClassPath.get (' id') .toString ()) If (! allMethodNames.includes (methodName)) {const tmp = Error.stackTraceLimit; Error.stackTraceLimit = 0; let errorMessage = `this member cannot have an 'override' modifier because it is not declared in the base class' ${superClassName}'` SemanticErrors.push (path.get ('key') .buildCodeFrameError (errorMessage, Error)); Error.stackTraceLimit = tmp });} state.file.set ('errors', semanticErrors) }, post (file) {console.log (file.get ('errors'));}); module.exports = overrideCheckerPlugin; test effect
Let's test it with the original code:
Class Animal {getName () {return'';}} class Dog extends Animal {override bak () {return 'wang';} override getName () {return' wang';}}
The print message is:
The error that bak does not exist in the parent class is correctly identified.
This is the end of the article on "how to implement Override of the principle of Typescript type checking". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to realize the Override of Typescript type checking principle". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.