2
type User = {
    name: string;
};
const flag: any = false;
let list1: User;
list1 = flag ? flag : 1;   // hope error

Why list1 can be 1, why not an error: Type '1' is not assignable to type 'User'

1 Answer 1

2

You are using any in the annotation to flag. any is by definition assignable to any type and assignable from any type. This means that the result of the expression flag ? flag : 1 will be any (since one of the results of the ternary expression is any the type of the expression is any | 1 which will get reduced to any).

Generally avoid any. If you really don't know a type at compile time use unknown. In this case removing the annotation yields an error as expected:

type User = {
    name: string;
};
const flag = false; // no annotation 
let list1: User;
list1 = flag ? flag : 1; // err
Sign up to request clarification or add additional context in comments.

4 Comments

also a general remark, it is better to use interface instead of type/class if you don't implement any methods on the interface u create (like domain objects with only the property definitions, or POJO in Java). It makes your class/type more lightweight
@RobRombouts type and interface basically the same thing in this case. class is a different beast. But type and interface are both types that are erased at compile time (they differ in what can be done with them in the type system but for this simple example there is no practical difference)
thanks for clearing that up for me, the advantage of an interface over a type is that an interface can be extended, type cant, got confused with that. I always use interface for that reason.
@RobRombouts types can be used as a base type for an interface. They can't extend other interfaces themselves (although intersections model this well enough). Types can't participate in merging so that extension avenue is closed. Either one will work fro simple cases, although I usually prefer interfaces too :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.