Skip to content

Commit

Permalink
improve error message
Browse files Browse the repository at this point in the history
  • Loading branch information
NyxCode committed Nov 11, 2024
1 parent 221b009 commit bd5d1e5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
12 changes: 6 additions & 6 deletions macros/src/types/named.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use proc_macro2::TokenStream;
use quote::quote;
use quote::{quote, quote_spanned};
use syn::{parse_quote, Field, FieldsNamed, Path, Result};

use syn::spanned::Spanned;
use crate::{
attr::{Attr, ContainerAttr, FieldAttr, Inflection, Optional, StructAttr},
deps::Dependencies,
Expand Down Expand Up @@ -108,10 +108,10 @@ fn format_field(
// `#[ts(optional)]` on field takes precedence, and is enforced **AT COMPILE TIME**
(_, Optional::Optional { nullable }) => (
// expression that evaluates to the string "?", but fails to compile if `ty` is not an `Option`.
quote! {{
use std::marker::PhantomData;
let actual: PhantomData<#ty> = PhantomData;
let must: PhantomData<std::option::Option<_>> = actual;
quote_spanned! { field.span() => {
fn check_that_field_is_option<T: #crate_rename::IsOption>(_: std::marker::PhantomData<T>) {}
let x: std::marker::PhantomData<#ty> = std::marker::PhantomData;
check_that_field_is_option(x);
"?"
}},
nullable,
Expand Down
10 changes: 10 additions & 0 deletions ts-rs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,16 @@ impl Dependency {
}
}

#[doc(hidden)]
#[diagnostic::on_unimplemented(
message = "`#[ts(optional)]` can only be used on fields of type `Option`",
note = "`#[ts(optional)]` was used on a field of type {Self}, which is not permitted",
label = ""
)]
pub trait IsOption {}

impl<T> IsOption for Option<T> {}

// generate impls for primitive types
macro_rules! impl_primitives {
($($($ty:ty),* => $l:literal),*) => { $($(
Expand Down

0 comments on commit bd5d1e5

Please sign in to comment.