The problem is about getting the actual type of function parameter to check it with checker.isNullableType
. I should find it from the function call statement, i.e. I can't select the string | null
statement directly.
type Action1<T> = (arg1: T) => void;
const fn: Action1<string | null> = (arg1: string | null): void => {};
fn(null);
Dev tools console:
var fnCallNode = sourceFile.statements[2].getChildAt(0).getChildAt(0);
var fnType = checker.getTypeAtLocation(fnCallNode);
console.log(checker.typeToString(fnType)); // "Action1<string | null>"
var parameterTypeDeclaration = fnType.getCallSignatures()[0].getParameters()[0].declarations[0];
var parameterType = checker.getTypeAtLocation(parameterTypeDeclaration);
console.log(checker.typeToString(parameterType)); // "T"
console.log(checker.isNullableType(parameterType)); // false
^ The desired result is to get the type "string | null"
for which checker.isNullable
is true
. I have no idea how to expand generic type into the actual one.
It turned out that I should start the search from the whole fn(null)
statement and use checker.getResolvedSignature
:
var fnCallNode = sourceFile.statements[2].getChildAt(0); // "fn(null)"
var fnCallSignature = checker.getResolvedSignature(fnCallNode);
var parameter = fnCallSignature.getParameters()[0];
var parameterType = checker.getTypeOfSymbolAtLocation(parameter, parameter.declarations[0]);
console.log(checker.typeToString(parameterType)); // "string | null"
console.log(checker.isNullableType(parameterType)); // true