Typescript unknown

Created By: chatGPT

TypeScript is a superset of JavaScript that adds static typing. One of the types provided by TypeScript is unknown, which represents a type-safe alternative to any. When you use unknown, you must do some type checking before performing operations on it, which increases type safety in your code.
// Using `unknown` in TypeScript

let userInput: unknown;

userInput = 5; // valid
userInput = "Hello"; // valid

if (typeof userInput === 'string') {
    console.log(userInput.toUpperCase()); // will work because we checked the type
} else {
    console.log('Not a string');
}
One common scenario for using unknown is when you're working with data from external sources, such as APIs, where the structure of the data might not be known in advance. This way, you can ensure that you handle the data correctly based on its actual type.
// Function that fetches user data

async function fetchUserData(url: string): Promise<unknown> {
    const response = await fetch(url);
    const data = await response.json();
    return data; // data is of type unknown
}

fetchUserData('https://api.example.com/user')
    .then(data => {
        // Check if data is an object before accessing properties
        if (typeof data === 'object' && data !== null) {
            console.log(data);
        } else {
            console.log('Received data is not an object');
        }
    });
To use unknown correctly, TypeScript requires you to narrow down the type before you can proceed with actions that depend on it. You can use type assertions if you're certain about the type after validation, but it should be done carefully.
// Using type assertion with `unknown`

let someValue: unknown = "TypeScript is great!";
let strLength: number = (someValue as string).length; // valid because we asserted the type
console.log(strLength); // Outputs: 20
Introduction And SetupVariablesData TypesAnyUnknownVoidNeverStringNumberBooleanArrayTupleEnumObjectInterfaceType AliasMethodsFunctionArrow FunctionReturn TypeParametersDefault ParametersOptional ParametersRest ParametersControl FlowIf StatementElse StatementSwitch StatementFor LoopWhile LoopDo While LoopFor...of LoopFor...in LoopBreak StatementContinue StatementFunctionsFunction OverloadingRecursive FunctionExpression FunctionOperatorsArithmetic OperatorsAssignment OperatorsComparison OperatorsLogical OperatorsBitwise OperatorsConditional (ternary) OperatorData StructuresArrayTupleObjectMapSetCommentsSingle Line CommentMulti Line CommentSyntaxType AnnotationsType InferenceNamespaceModuleExportImportDecoratorsAmbient DeclarationsEvent HandlingEvent ListenersAddEventListenerRemoveEventListenerError HandlingTry...catch StatementThrow StatementFinally BlockCustom Error TypesAsync AwaitPromisesGenericsConditional TypesMapped TypesIntersection TypesUnion TypesLiteral TypesDiscriminated UnionsType GuardsTypeof GuardInstanceof GuardAssertion FunctionsModule Augmentation