TypeScript face object two

interface BaseButtonProps { icon: string; } function printButton(buttonProps: BaseButtonProps) { console.log(buttonProps.icon); } let myObj = {icon:'add'}; printButton(myObj);

When calling the printButtonh function, the type checker looks at the parameter object and asks for the icon attribute.

interface BaseButtonProps { icon?: string; }

interface BaseButtonProps { readonly icon?: string; }

function greetNane<T>(name:T):T{ return name } let myIdentity: <T>(name: T) => T = greetNane;

We can also define the generic function using the literal size of the object with the calling signature.

function greetNane<T>(name:T):T{
    return name
}
let myIdentity: {<T>(name: T): T} = greetNane;

This leads us to write the first generic interface. We take the font size of the object in the above example as an interface.

interface GenericIdentityFn<T> {
    (arg: T): T;
}

function greetNane<T>(name:T):T{
    return name
}

let myIdentity: GenericIdentityFn<number> = greetNane;

class GenericNumber<T> { zeroValue: T; add: (x: T, y: T) => T; } let myGenericNumber = new GenericNumber<number>(); myGenericNumber.zeroValue = 0; myGenericNumber.add = function(x, y) { return x + y; };

Generic classes look almost the same as generic interfaces. Generic classes use (< >) to encode generic types followed by class names.

interface Lengthwise { length: number; } function loggingIdentity<T extends Lengthwise>(arg: T): T { console.log(arg.length); // Now we know it has a .length property, so no more error return arg; }

Now the generic function is defined as a constraint.

Leave a Reply

Your email address will not be published. Required fields are marked *