Here is a TypeScript interface that I am working with:
interface MyInterface {
property1?: string;
property2?: string;
};
type InterfaceKey = keyof MyInterface;
The following code snippet demonstrates how an object is created based on the MyInterface
interface. It includes a function named verifyObjectProperty
which enables the user to provide an InterfaceKey
('property1' or 'property2') as the second parameter.
This function ensures that the object contains a string value for the specified key, preventing it from being undefined.
// - Create an object based on the interface
const myObject: MyInterface = {
property1: 'a string',
}
const verifyObjectProperty = (
objectToVerify: MyInterface,
properyToVerify: InterfaceKey
): MyInterface => {
// - Check if the object has the desired property
if (objectToVerify[properyToVerify] === undefined) {
objectToVerify[properyToVerify] = 'a new string';
}
// - Return the updated object
return myObject;
};
The goal is to modify the verifyObjectProperty
function so that it outputs a TypeScript interface indicating which strings are guaranteed to be present.
const verifiedObject = verifyObjectProperty(myObject, 'property1');
type property1 = typeof verifiedObject['property1']; // string
type property2 = typeof verifiedObject['property2']; // string | undefined