class Thing {
protected x?: never
}
type Test = boolean | Thing
let t1: Test = new Thing() // OK: allowed
let t2: Test = {} // BAD: allowed
let t3: Test = 3424234 // OK: disallowed
let t4: Test = "3424" // OK: disallowed
console.log(Object.keys(t1)) // BAD: x affects Object.keys / for-in loops
console.log(t2)
console.log(t3)
console.log(t4)
import{z,BRAND}from"zod";constCat=z.object({name:z.string()}).brand<"Cat">();typeCat=z.infer<typeofCat>;constcat=Cat.parse({name:"simba"});// or const cat = { name: "simba" } as Cat;constcatBrand=cat[BRAND];typeU=typeofcatBrand;// { Cat: true }console.log(catBrand);// undefined
still can access cat[BRAND]
type of cat[BRAND] and value of cat[BRAND] mismatched
1 is unsatisfying but overall is not a problem, because nobody is going to do that
2 is an easy fix, just add optional modifier, although it still mislead some to believe it may return { Cat: true }
overall I think zod solution is practically perfect
In general TypeScript requires a runtime assertion in the absence of a compile time type assertion.
// Don't export this from the moduledeclareconstvalidCat:uniquesymbol;typeCat={name:string;[validCat]:true;};functionassertValidCat(maybeCat:Record<PropertyKey,unknown>):assertsmaybeCatisCat{constentries=Object.entries(maybeCat);if(entries.length===1&&entries[0][0]==='name'&&entries[0][1]==='simba')return;thrownewError('Not a Cat');}// outside of moduleconstcatMaybe={name:'simba'};// const catMaybe: { name: string }assertValidCat(catMaybe);constcatDefinitely=catMaybe;// const catDefinitely: Cat, const catMaybe: Catconsole.log(Object.keys(catDefinitely).length);// 1
Typescript's assignability has edge cases that may surprise some people, perhaps the most infamous one is that assignments are not subject to excess property checks.
So it could be argued:
typeAB={a:number;b:number;x:never};// For nominal typing this assignment should// ideally error as the literal isn't branded to begin with.constab:AB={a:1,b:2};
Compare that to
declareconstvalidAB:uniquesymbol;declareconstvalidBA:uniquesymbol;typeAB={a:number;b:number;[validAB]:true;};typeBA={a:number;b:number;[validBA]:true;};// https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functionsfunctionassertAB(maybeAB:Record<PropertyKey,unknown>):assertsmaybeABisAB{constkeys=Object.keys(maybeAB);if (keys.length===2&&typeofmaybeAB['a']==='number'&&typeofmaybeAB['b']==='number')return;thrownewError('Not an AB type');}// const ab: AB = {a:1, b:2}// error: Property '[validAB]' is missing in type '{ a: number; b: number; }' but required in type 'AB'.(2741)// const ba: BA = {a:1, b:2}// error: Property '[validBA]' is missing in type '{ a: number; b: number; }' but required in type 'BA'.(2741)constab={a:1,b:2};// unbranded: const ab: { a: number; b: number; }assertAB(ab);// now branded: const ab: AB// … and IntelliSense only shows properties `a` and `b`// const ba: BA = ab;// error: Property '[validBA]' is missing in type 'AB' but required in type 'BA'.(2741)console.log(ab);
Does not look like a proper solution:
not sure i understand this
let t2: Test = {}is expected becausexis supposed to be not existDo this instead:
Symbols are enumerable by default but
Object.keysandfor-inwork only withstringprops.So it fixes all the above issues.
If you also want to prevent
Object.assigncopies, add this:no, dont mess with the runtime
the purspose is to hide the type while making it an nominal type, the result of your original example is actually correct and is expected
Have you looked at zod brand?
github.com/colinhacks/zod#brand
I think zod brand is a very smart solution
but it has 2 problems
cat[BRAND]cat[BRAND]and value ofcat[BRAND]mismatched1 is unsatisfying but overall is not a problem, because nobody is going to do that
2 is an easy fix, just add optional modifier, although it still mislead some to believe it may return
{ Cat: true }overall I think zod solution is practically perfect
update:
I missed one point:
to assign Cat type to a variable, you either do
since we want to avoid type assertion if possible
then we are left with:
which is slightly unintuitive
ideally, we want
but this will error using zod method because it is missing symbol properties
In general TypeScript requires a runtime assertion in the absence of a compile time type assertion.
Playground
You can even do this to primitive types
Assertion Functions
Source
A type predicate can be used to a similar end.
In a sense the fact that
even works is no better than
avoid type assertion because it is prone to error
playground
You've missed the point.
Typescript's assignability has edge cases that may surprise some people, perhaps the most infamous one is that assignments are not subject to excess property checks.
So it could be argued:
Compare that to
playground