Ts-morph: Constant types break isXType functions

Created on 26 Mar 2018  路  7Comments  路  Source: dsherret/ts-morph

I might be missing something obvious here... but getting types for constant variable declarations doesn't work as expected, getting the apparent type doesn't seem to resolve the problem.

Demo:

import Project, { TypeGuards } from 'ts-simple-ast'

const project = new Project()

const file = project.createSourceFile('file.ts', `
  export const a = 'hi'
  export const b = 1
`)

file.getExportedDeclarations()
  .filter(TypeGuards.isVariableDeclaration)
  .forEach(declaration => {
    const type = declaration.getType()
    const apparentType = type.getApparentType()
    console.log(declaration.getName())
    console.log(type.getText(), type.isNumberType(), type.isStringType())
    console.log(apparentType.getText(), apparentType.isNumberType(), apparentType.isStringType())
    console.log()
  })

Output:

a
"hi" false false // => Expected false, true
String false false // => I'd like to get type string

b
1 false false // => Expected true, false
Number false false // => I'd like to get type number
question

All 7 comments

Hi @Gerrit0, those are TypeFlags.NumberLiteral and TypeFlags.StringLiteral types. The isStringType() is seeing if the type has a flag of TypeFlags.String, which in this case it doesn't.

I'll add methods for NumberLiteral, StringLiteral, and BooleanLiteral because those are currently missing.

Opened #291 for this.

Ah, that makes sense, thanks!

Is there any way for me to convert a type from, say, a numeric literal to type number?

Found it! There's a getBaseTypeOfLiteralType() on ts.TypeChecker.

If you want, you can temporarily fall back to the compiler API...

const baseType = project.getTypeChecker().compilerObject.getBaseTypeOfLiteralType(type.compilerType);

...but I will open up an issue and wrap this soon.

Ok, I implemented all this. I'll comment back when v10 is released (sometime this week or next... feel free to clone the dev branch in case you need this now).

// this will work in v10
const numberType = numberLiteralType.getBaseTypeOfLiteralType();

I'm going to close this issue for now, but let me know if there's anything else you need.

Thanks much! I'm using the code you posted above for now, but will certainly switch to V10 once released. type.isLiteralType might be useful, but is also trivial to write myself.

Good point. I meant to add that. Thanks!

That will be in v10 as well.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

HamedFathi picture HamedFathi  路  3Comments

GrandSchtroumpf picture GrandSchtroumpf  路  3Comments

dyatko picture dyatko  路  3Comments

pierregallard picture pierregallard  路  4Comments

allenhwkim picture allenhwkim  路  4Comments