Issue
This code:
interface Dog {
name?: string;
size?: number;
}
const entity: Dog = {
name: 'max',
}
const name: string = entity.name;
Causes this error:
Type 'string | undefined' is not assignable to type 'string'.
I can avoid the error by removing the entity
type:
interface Dog {
name?: string;
size?: number;
}
const entity = {
name: 'max',
}
const name: string = entity.name;
But then I lose the auto-complete feature.
Is there a way to win both? To have autocomplete, and let the code know which keys are there based on the initializer?
E.g. using Required<Dog>
isn't a good solution because I don't want to initialize size
. The real use-case I have actually has a much bigger interface.
Solution
What I do is to define a generic identity check function that can be used for any interfaces:
function identityCheck<T = never>() {
return <I>(input: I & T) => input as I;
}
then create a concrete check-function for the Dog
interface:
const dogIdentity = identityCheck<Dog>();
finally use it to create the constant:
const myDog = dogIdentity({
name: 'bello',
})
// name is of type string
myDog.name.slice();
Answered By - TmTron
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.