0

My snippet.

signUpInfo: {code: string, message: string} 
     = new Subject<{code: string, message: string}>();

The error Atom editor gives me.

Type 'Subject<{code: string, message: string}>' is not assignable to type '{code: string, message: string}'. Property 'code' is missing in type 'Subject<{code: string, message: string}>'.

typescript error

Removing the typings in the variable, replacing by type any or {} removes the error.

signUpInfo = new Subject<{code: string, message: string}>();
signUpInfo: any = new Subject<{code: string, message: string}>();
signUpInfo: {} = new Subject<{code: string, message: string}>();
signUpInfo = new Subject<{code: string, message: string}>();
signUpInfo: any[] = new Subject<model[]>();

I am used to put a typeings on every variable in TS, I have no problems when passing regular types such as string number booleans etc. but when passing array or object as Subject variable typings it seems that Im not allowed to it.

What is the correct way of typing an object or array Subject variable in typescript?

2
  • 1
    A Subject<Message> is like a phone: it emits messages. A phone is not a message. The type of your variable should be the type you used on the right side of the equal sign: Subject<{code: string, message: string}> Commented Sep 10, 2017 at 17:34
  • I see thanks @JBNizet Commented Sep 10, 2017 at 17:37

1 Answer 1

3

The correct way is to set:

signUpInfo: Subject<{code: string, message: string}> = new Subject<{code: string, message: string}>();

Actually I think you don't even need to set the type because it's automatically assumed when you're assigning it an instance of Subject<{code: string, message: string}>. So if you try to call signUpInfo.next(1) the compiler will throw a type error.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you now i get it why there are a lot subject variable snippets having no typings

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.