0

How can I write a date using typescript?

I select a date in the picker, and try to write it in the state, but I get an error, how to do it correctly?

const [dateFrom, setDateFrom] = useState<Date | null>(new Date());

onChange={(e, v) => {
  setDateFrom(v);
}}

ype '(e: Date | null, v: Date | null) => void' is not assignable to type '(date: Date | null, value?: string | null | undefined) => void'. Types of parameters 'v' and 'value' are incompatible. Type 'string | null | undefined' is not assignable to type 'Date | null'. Type 'undefined' is not assignable to type 'Date | null'.

2 Answers 2

1

The error tells you that you are not doing the proper checks on the value:

Type 'string | null | undefined' is not assignable to type 'Date | null'. Type 'undefined' is not assignable to type 'Date | null'.

v could be string, null, undefined and you are assigning it to a variable that is Date or null. They are not compatible types.

You should cast create a Date in case v is a string, or assign null otherwise

onChange={(e, v) => {
 setDateFrom(typeof v === 'string' ? new Date(v) : null);
}}
Sign up to request clarification or add additional context in comments.

Comments

0
const [dateFrom, setDateFrom] = useState<Date | undefined>(new Date());

onChange={(e, v) => {
  setDateFrom(new Date(v));
}}

Comments

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.