The present invention provides an agent for the prophylaxis or treatment of autoimmune diseases (e.g., psoriasis, rheumatoid arthritis, inflammatory bowel disease, Sjogrens syndrome, Behcets disease, multiple sclerosis, systemic lupus erythematosus etc.) and the like, which has a superior Tyk2 inhibitory action.The present invention relates to a compound represented by the formulawherein each symbol is as defined in the specification, or a salt thereof.